Browse Source

resolve conflicts

Trevor Baron 7 years ago
parent
commit
5f0e100ade
100 changed files with 39968 additions and 32365 deletions
  1. 5 0
      .gitignore
  2. 1 1
      .vscode/launch.json
  3. 13 6
      .vscode/tasks.json
  4. 10456 8839
      Playground/babylon.d.txt
  5. 4 0
      Playground/scenes/BoomBox/BoomBox.gltf
  6. 19 4
      Tools/Gulp/config.json
  7. 37 13
      Tools/Gulp/gulpfile.js
  8. 0 69
      Viewer/dist/viewer.js
  9. 0 69
      Viewer/dist/viewer.min.js
  10. 5 0
      Viewer/src/configuration/configuration.ts
  11. 46 0
      Viewer/src/viewer/viewer.ts
  12. 2 2
      dist/babylon.glTF2Interface.d.ts
  13. 2188 589
      dist/preview release/babylon.d.ts
  14. 52 51
      dist/preview release/babylon.js
  15. 2198 497
      dist/preview release/babylon.max.js
  16. 53 52
      dist/preview release/babylon.worker.js
  17. 2805 1206
      dist/preview release/customConfigurations/minimalGLTFViewer/babylon.d.ts
  18. 55 54
      dist/preview release/customConfigurations/minimalGLTFViewer/babylon.js
  19. 3274 2007
      dist/preview release/customConfigurations/minimalGLTFViewer/babylon.max.js
  20. 3276 2009
      dist/preview release/customConfigurations/minimalGLTFViewer/es6.js
  21. 2200 499
      dist/preview release/es6.js
  22. 13 1
      dist/preview release/gui/babylon.gui.d.ts
  23. 42 5
      dist/preview release/gui/babylon.gui.js
  24. 2 2
      dist/preview release/gui/babylon.gui.min.js
  25. 13 1
      dist/preview release/gui/babylon.gui.module.d.ts
  26. 1 1
      dist/preview release/gui/package.json
  27. 1 1
      dist/preview release/inspector/package.json
  28. 49 22
      dist/preview release/loaders/babylon.glTF1FileLoader.d.ts
  29. 93 78
      dist/preview release/loaders/babylon.glTF1FileLoader.js
  30. 2 2
      dist/preview release/loaders/babylon.glTF1FileLoader.min.js
  31. 227 382
      dist/preview release/loaders/babylon.glTF2FileLoader.d.ts
  32. 1129 1494
      dist/preview release/loaders/babylon.glTF2FileLoader.js
  33. 2 2
      dist/preview release/loaders/babylon.glTF2FileLoader.min.js
  34. 220 377
      dist/preview release/loaders/babylon.glTFFileLoader.d.ts
  35. 1159 1514
      dist/preview release/loaders/babylon.glTFFileLoader.js
  36. 3 3
      dist/preview release/loaders/babylon.glTFFileLoader.min.js
  37. 1 1
      dist/preview release/loaders/babylon.objFileLoader.d.ts
  38. 4 7
      dist/preview release/loaders/babylon.objFileLoader.js
  39. 1 1
      dist/preview release/loaders/babylon.objFileLoader.min.js
  40. 1 1
      dist/preview release/loaders/babylon.stlFileLoader.d.ts
  41. 4 7
      dist/preview release/loaders/babylon.stlFileLoader.js
  42. 1 1
      dist/preview release/loaders/babylon.stlFileLoader.min.js
  43. 1175 1536
      dist/preview release/loaders/babylonjs.loaders.js
  44. 3 3
      dist/preview release/loaders/babylonjs.loaders.min.js
  45. 221 378
      dist/preview release/loaders/babylonjs.loaders.module.d.ts
  46. 1 1
      dist/preview release/loaders/package.json
  47. 1 1
      dist/preview release/materialsLibrary/package.json
  48. 1 1
      dist/preview release/postProcessesLibrary/package.json
  49. 1 1
      dist/preview release/proceduralTexturesLibrary/package.json
  50. 249 0
      dist/preview release/serializers/babylonjs.serializers.module.d.ts
  51. 1 1
      dist/preview release/serializers/package.json
  52. 4873 7839
      dist/preview release/typedocValidationBaseline.json
  53. 64 64
      dist/preview release/viewer/babylon.viewer.js
  54. 1 1
      dist/preview release/viewer/package.json
  55. 21 2
      dist/preview release/what's new.md
  56. 45 7
      gui/src/controls/line.ts
  57. 4 7
      loaders/src/OBJ/babylon.objFileLoader.ts
  58. 4 7
      loaders/src/STL/babylon.stlFileLoader.ts
  59. 42 12
      loaders/src/glTF/1.0/babylon.glTFLoader.ts
  60. 0 24
      loaders/src/glTF/1.0/babylon.glTFLoaderUtils.ts
  61. 78 90
      loaders/src/glTF/2.0/Extensions/KHR_lights.ts
  62. 55 29
      loaders/src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts
  63. 92 92
      loaders/src/glTF/2.0/Extensions/MSFT_lod.ts
  64. 876 1178
      loaders/src/glTF/2.0/babylon.glTFLoader.ts
  65. 41 49
      loaders/src/glTF/2.0/babylon.glTFLoaderExtension.ts
  66. 57 260
      loaders/src/glTF/2.0/babylon.glTFLoaderInterfaces.ts
  67. 21 0
      loaders/src/glTF/2.0/babylon.glTFLoaderUtilities.ts
  68. 0 36
      loaders/src/glTF/2.0/babylon.glTFLoaderUtils.ts
  69. 55 48
      loaders/src/glTF/babylon.glTFFileLoader.ts
  70. 1 1
      package.json
  71. 0 4
      sandbox/index.js
  72. 8 3
      src/Engine/babylon.engine.ts
  73. 94 0
      src/Helpers/babylon.videoDome.ts
  74. 20 0
      src/Lights/Shadows/babylon.shadowGenerator.ts
  75. 299 298
      src/Loading/Plugins/babylon.babylonFileLoader.ts
  76. 224 33
      src/Loading/babylon.sceneLoader.ts
  77. 29 2
      src/Materials/Background/babylon.backgroundMaterial.ts
  78. 425 271
      src/Materials/PBR/babylon.pbrBaseMaterial.ts
  79. 67 0
      src/Materials/PBR/babylon.pbrMaterial.ts
  80. 9 0
      src/Materials/PBR/babylon.pbrMetallicRoughnessMaterial.ts
  81. 9 0
      src/Materials/PBR/babylon.pbrSpecularGlossinessMaterial.ts
  82. 26 1
      src/Materials/Textures/babylon.baseTexture.ts
  83. 28 0
      src/Materials/Textures/babylon.cubeTexture.ts
  84. 28 0
      src/Materials/Textures/babylon.renderTargetTexture.ts
  85. 4 1
      src/Materials/Textures/babylon.videoTexture.ts
  86. 490 8
      src/Materials/babylon.material.ts
  87. 8 3
      src/Materials/babylon.materialHelper.ts
  88. 14 0
      src/Materials/babylon.standardMaterial.ts
  89. 373 116
      src/Math/babylon.math.ts
  90. 2 2
      src/Mesh/babylon.mesh.ts
  91. 75 38
      src/Mesh/babylon.mesh.vertexData.ts
  92. 1 1
      src/Mesh/babylon.transformNode.ts
  93. 33 30
      src/Mesh/babylon.vertexBuffer.ts
  94. 6 0
      src/Particles/babylon.solidParticle.ts
  95. 47 14
      src/Particles/babylon.solidParticleSystem.ts
  96. 2 2
      src/Rendering/babylon.renderingGroup.ts
  97. 1 0
      src/Shaders/ShadersInclude/backgroundUboDeclaration.fx
  98. 1 0
      src/Shaders/ShadersInclude/backgroundVertexDeclaration.fx
  99. 5 0
      src/Shaders/ShadersInclude/defaultFragmentDeclaration.fx
  100. 0 0
      src/Shaders/ShadersInclude/defaultUboDeclaration.fx

+ 5 - 0
.gitignore

@@ -24,6 +24,7 @@ postProcessLibrary/src/**/*.js
 inspector/src/**/*.js
 serializers/src/**/*.js
 gui/src/**/*.js
+viewer/src/**/*.js
 tests/unit/**/*.js
 !tests/unit/karma.conf.js
 
@@ -169,3 +170,7 @@ localDev/src/*
 /localDev/src/index.js
 package-lock.json
 dist/preview release/package/
+
+# viewer dist files
+/Viewer/dist/viewer.js
+/Viewer/dist/viewer.min.js

+ 1 - 1
.vscode/launch.json

@@ -1,5 +1,5 @@
 {
-    "version": "0.1.0",
+    "version": "2.0.0",
     "configurations": [
         {
             "name": "Launch Viewer (Chrome)",

+ 13 - 6
.vscode/tasks.json

@@ -1,19 +1,26 @@
 {
     // See https://go.microsoft.com/fwlink/?LinkId=733558
     // for the documentation about the tasks.json format
-    "version": "0.1.0",
+    "version": "2.0.0",
     "command": "gulp",
-    "isShellCommand": true,
     "args": [],
-    "showOutput": "always",
+    "type": "shell",
     "options": {
         "cwd": "${workspaceRoot}/Tools/Gulp"
     },
+    "presentation": {
+        "echo": true,
+        "reveal": "always",
+        "focus": false,
+        "panel": "shared"
+    },
     "tasks": [
         { 
-            "taskName": "run",
-            // Hijack Test Command for easy shortcut
-            "isTestCommand": true,
+            "label": "run",
+            "group": {
+                "kind": "build",
+                "isDefault": true
+            },
             "isBackground": true,
             "problemMatcher": {
                 "owner": "typescript",

File diff suppressed because it is too large
+ 10456 - 8839
Playground/babylon.d.txt


+ 4 - 0
Playground/scenes/BoomBox/BoomBox.gltf

@@ -158,15 +158,19 @@
   ],
   "textures": [
     {
+      "name": "baseColor",
       "source": 0
     },
     {
+      "name": "occlusionRoughnessMetallic",
       "source": 1
     },
     {
+      "name": "normal",
       "source": 2
     },
     {
+      "name": "emissive",
       "source": 3
     }
   ]

+ 19 - 4
Tools/Gulp/config.json

@@ -86,7 +86,8 @@
             "nullEngine",
             "instrumentation",
             "backgroundMaterial",
-            "environmentHelper"
+            "environmentHelper",
+            "videoDome"
         ],
         "minimal": [
             "freeCamera",
@@ -178,6 +179,7 @@
                 "../../src/babylon.mixins.js",
                 "../../src/Engine/babylon.webgl2.js",
                 "../../src/Tools/babylon.decorators.js",
+                "../../src/Tools/babylon.deferred.js",
                 "../../src/Tools/babylon.observable.js",
                 "../../src/Tools/babylon.smartArray.js",
                 "../../src/Tools/babylon.tools.js",
@@ -1120,6 +1122,16 @@
                 "backgroundMaterial",
                 "additionalTextures"
             ]
+        },
+        "videoDome": {
+            "files": [
+                "../../src/Helpers/babylon.videoDome.js"
+            ],
+            "dependUpon": [
+                "core",
+                "meshBuilder",
+                "additionalTextures"
+            ]
         }
     },
     "typescript": [
@@ -1460,9 +1472,9 @@
             {
                 "files": [
                     "../../loaders/src/glTF/babylon.glTFFileLoader.ts",
+                    "../../loaders/src/glTF/2.0/babylon.glTFLoaderUtilities.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoaderInterfaces.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoader.ts",
-                    "../../loaders/src/glTF/2.0/babylon.glTFLoaderUtils.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoaderExtension.ts",
                     "../../loaders/src/glTF/2.0/Extensions/MSFT_lod.ts",
                     "../../loaders/src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts",
@@ -1480,9 +1492,9 @@
                     "../../loaders/src/glTF/1.0/babylon.glTFLoaderExtension.ts",
                     "../../loaders/src/glTF/1.0/babylon.glTFBinaryExtension.ts",
                     "../../loaders/src/glTF/1.0/babylon.glTFMaterialsCommonExtension.ts",
+                    "../../loaders/src/glTF/2.0/babylon.glTFLoaderUtilities.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoaderInterfaces.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoader.ts",
-                    "../../loaders/src/glTF/2.0/babylon.glTFLoaderUtils.ts",
                     "../../loaders/src/glTF/2.0/babylon.glTFLoaderExtension.ts",
                     "../../loaders/src/glTF/2.0/Extensions/MSFT_lod.ts",
                     "../../loaders/src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts",
@@ -1524,6 +1536,9 @@
             "distOutputDirectory": "/serializers/",
             "buildAsModule": true,
             "moduleName": "babylonjs-serializers",
+            "extraDeclarations": [
+                "../../dist/babylon.glTF2Interface.d.ts"
+            ],
             "outputFilename": "babylonjs.serializers",
             "moduleDeclaration": "BJSSerializers",
             "extendsRoot": true
@@ -1678,4 +1693,4 @@
             ]
         }
     }
-}
+}

+ 37 - 13
Tools/Gulp/gulpfile.js

@@ -325,7 +325,9 @@ var buildExternalLibraries = function (settings) {
             let dtsFiles = files.map(function (filename) {
                 return filename.replace(".js", ".d.ts");
             });
-
+            if (settings.build.extraDeclarations) {
+                settings.build.extraDeclarations.forEach(file => { dtsFiles.unshift(file) })
+            }
             let dtsTask = gulp.src(dtsFiles)
                 .pipe(concat(settings.build.outputFilename + ".module.d.ts"))
                 .pipe(replace(referenceSearchRegex, ""))
@@ -405,6 +407,8 @@ var buildExternalLibrary = function (library, settings, watch) {
             .pipe(gulp.dest(outputDirectory));
         /*}*/
 
+
+
         var dts = tsProcess.dts
             .pipe(concat(library.output))
             .pipe(replace(referenceSearchRegex, ""))
@@ -432,22 +436,42 @@ var buildExternalLibrary = function (library, settings, watch) {
                 let build = wpBuild
                     .pipe(addModuleExports(library.moduleDeclaration, false, false, true));
 
+                let unminifiedOutpus = [];
+                let minifiedOutputs = [];
                 settings.build.outputs.forEach(out => {
-                    let outBuild = build;
                     if (out.minified) {
-                        outBuild = build
-                            .pipe(uglify())
-                            .pipe(optimisejs())
+                        out.destination.forEach(dest => {
+                            minifiedOutputs.push(dest);
+                        });
+                    } else {
+                        out.destination.forEach(dest => {
+                            unminifiedOutpus.push(dest);
+                        });
                     }
+                });
+
+                function processDestination(dest) {
+                    var outputDirectory = config.build.outputDirectory + dest.outputDirectory;
+                    build = build
+                        .pipe(rename(dest.filename.replace(".js", library.noBundleInName ? '.js' : ".bundle.js")))
+                        .pipe(gulp.dest(outputDirectory));
+                }
+
+                unminifiedOutpus.forEach(dest => {
+                    processDestination(dest);
+                });
+
+                if (minifiedOutputs.length) {
+                    build = build
+                        .pipe(uglify())
+                        .pipe(optimisejs())
+                }
+
+                minifiedOutputs.forEach(dest => {
+                    processDestination(dest);
+                });
 
-                    out.destination.forEach(dest => {
-                        var outputDirectory = config.build.outputDirectory + dest.outputDirectory;
-                        let destBuild = outBuild
-                            .pipe(rename(dest.filename.replace(".js", library.noBundleInName ? '.js' : ".bundle.js")))
-                            .pipe(gulp.dest(outputDirectory));
-                        sequence.push(destBuild);
-                    });
-                })
+                sequence.push(build);
             } else {
                 sequence.push(
                     wpBuild

File diff suppressed because it is too large
+ 0 - 69
Viewer/dist/viewer.js


File diff suppressed because it is too large
+ 0 - 69
Viewer/dist/viewer.min.js


+ 5 - 0
Viewer/src/configuration/configuration.ts

@@ -75,6 +75,11 @@ export interface IModelConfiguration {
     parentObjectIndex?: number; // the index of the parent object of the model in the loaded meshes array.
 
     castShadow?: boolean;
+    normalize?: boolean | {
+        center?: boolean;
+        unitSize?: boolean;
+        parentIndex?: number;
+    }; // shoud the model be scaled to unit-size
 
     title: string;
     subtitle?: string;

+ 46 - 0
Viewer/src/viewer/viewer.ts

@@ -529,6 +529,52 @@ export abstract class AbstractViewer {
                 Tags.AddTagsTo(mesh, 'castShadow');
             });
         }
+
+        if (modelConfiguration.normalize) {
+            let center = false;
+            let unitSize = false;
+            let parentIndex;
+            if (modelConfiguration.normalize === true) {
+                center = true;
+                unitSize = true;
+                parentIndex = 0;
+            } else {
+                center = !!modelConfiguration.normalize.center;
+                unitSize = !!modelConfiguration.normalize.unitSize;
+                parentIndex = modelConfiguration.normalize.parentIndex;
+            }
+
+            let meshesToNormalize: Array<AbstractMesh> = [];
+            if (parentIndex !== undefined) {
+                meshesToNormalize.push(focusMeshes[parentIndex]);
+            } else {
+                meshesToNormalize = meshesWithNoParent;
+            }
+
+            if (unitSize) {
+                meshesToNormalize.forEach(mesh => {
+                    console.log(mesh.scaling.x)
+                    mesh.normalizeToUnitCube(true);
+                    mesh.computeWorldMatrix(true);
+                    console.log(mesh.scaling.x)
+                });
+            }
+            if (center) {
+                meshesToNormalize.forEach(mesh => {
+                    const boundingInfo = mesh.getHierarchyBoundingVectors(true);
+                    const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
+                    const halfSizeVec = sizeVec.scale(0.5);
+                    const center = boundingInfo.min.add(halfSizeVec);
+                    mesh.position = center.scale(-1);
+
+                    // Set on ground.
+                    mesh.position.y += halfSizeVec.y;
+
+                    // Recompute Info.
+                    mesh.computeWorldMatrix(true);
+                });
+            }
+        }
     }
 
     public dispose() {

+ 2 - 2
dist/babylon.glTF2Interface.d.ts

@@ -22,7 +22,7 @@ declare module BABYLON.GLTF2 {
         SCALE = "scale",
         WEIGHTS = "weights",
     }
-    const enum AnimationInterpolation {
+    const enum AnimationSamplerInterpolation {
         LINEAR = "LINEAR",
         STEP = "STEP",
         CUBICSPLINE = "CUBICSPLINE",
@@ -110,7 +110,7 @@ declare module BABYLON.GLTF2 {
     }
     interface IAnimationSampler extends IProperty {
         input: number;
-        interpolation?: AnimationInterpolation;
+        interpolation?: AnimationSamplerInterpolation;
         output: number;
     }
     interface IAnimation extends IChildRootProperty {

File diff suppressed because it is too large
+ 2188 - 589
dist/preview release/babylon.d.ts


File diff suppressed because it is too large
+ 52 - 51
dist/preview release/babylon.js


File diff suppressed because it is too large
+ 2198 - 497
dist/preview release/babylon.max.js


File diff suppressed because it is too large
+ 53 - 52
dist/preview release/babylon.worker.js


File diff suppressed because it is too large
+ 2805 - 1206
dist/preview release/customConfigurations/minimalGLTFViewer/babylon.d.ts


File diff suppressed because it is too large
+ 55 - 54
dist/preview release/customConfigurations/minimalGLTFViewer/babylon.js


File diff suppressed because it is too large
+ 3274 - 2007
dist/preview release/customConfigurations/minimalGLTFViewer/babylon.max.js


File diff suppressed because it is too large
+ 3276 - 2009
dist/preview release/customConfigurations/minimalGLTFViewer/es6.js


File diff suppressed because it is too large
+ 2200 - 499
dist/preview release/es6.js


+ 13 - 1
dist/preview release/gui/babylon.gui.d.ts

@@ -436,7 +436,19 @@ declare module BABYLON.GUI {
         _draw(parentMeasure: Measure, context: CanvasRenderingContext2D): void;
         _measure(): void;
         protected _computeAlignment(parentMeasure: Measure, context: CanvasRenderingContext2D): void;
-        _moveToProjectedPosition(projectedPosition: Vector3): void;
+        /**
+         * Move one end of the line given 3D cartesian coordinates.
+         * @param position Targeted world position
+         * @param scene Scene
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        moveToVector3(position: Vector3, scene: Scene, end?: boolean): void;
+        /**
+         * Move one end of the line to a position in screen absolute space.
+         * @param projectedPosition Position in screen absolute space (X, Y)
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        _moveToProjectedPosition(projectedPosition: Vector3, end?: boolean): void;
     }
 }
 

+ 42 - 5
dist/preview release/gui/babylon.gui.js

@@ -2600,11 +2600,48 @@ var BABYLON;
                 this._currentMeasure.left = Math.min(this._x1.getValue(this._host), this._effectiveX2) - this._lineWidth / 2;
                 this._currentMeasure.top = Math.min(this._y1.getValue(this._host), this._effectiveY2) - this._lineWidth / 2;
             };
-            Line.prototype._moveToProjectedPosition = function (projectedPosition) {
-                this.x1 = (projectedPosition.x + this._linkOffsetX.getValue(this._host)) + "px";
-                this.y1 = (projectedPosition.y + this._linkOffsetY.getValue(this._host)) + "px";
-                this._x1.ignoreAdaptiveScaling = true;
-                this._y1.ignoreAdaptiveScaling = true;
+            /**
+             * Move one end of the line given 3D cartesian coordinates.
+             * @param position Targeted world position
+             * @param scene Scene
+             * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+             */
+            Line.prototype.moveToVector3 = function (position, scene, end) {
+                if (end === void 0) { end = false; }
+                if (!this._host || this._root !== this._host._rootContainer) {
+                    BABYLON.Tools.Error("Cannot move a control to a vector3 if the control is not at root level");
+                    return;
+                }
+                var globalViewport = this._host._getGlobalViewport(scene);
+                var projectedPosition = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), scene.getTransformMatrix(), globalViewport);
+                this._moveToProjectedPosition(projectedPosition, end);
+                if (projectedPosition.z < 0 || projectedPosition.z > 1) {
+                    this.notRenderable = true;
+                    return;
+                }
+                this.notRenderable = false;
+            };
+            /**
+             * Move one end of the line to a position in screen absolute space.
+             * @param projectedPosition Position in screen absolute space (X, Y)
+             * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+             */
+            Line.prototype._moveToProjectedPosition = function (projectedPosition, end) {
+                if (end === void 0) { end = false; }
+                var x = (projectedPosition.x + this._linkOffsetX.getValue(this._host)) + "px";
+                var y = (projectedPosition.y + this._linkOffsetY.getValue(this._host)) + "px";
+                if (end) {
+                    this.x2 = x;
+                    this.y2 = y;
+                    this._x2.ignoreAdaptiveScaling = true;
+                    this._y2.ignoreAdaptiveScaling = true;
+                }
+                else {
+                    this.x1 = x;
+                    this.y1 = y;
+                    this._x1.ignoreAdaptiveScaling = true;
+                    this._y1.ignoreAdaptiveScaling = true;
+                }
             };
             return Line;
         }(GUI.Control));

File diff suppressed because it is too large
+ 2 - 2
dist/preview release/gui/babylon.gui.min.js


+ 13 - 1
dist/preview release/gui/babylon.gui.module.d.ts

@@ -442,7 +442,19 @@ declare module BABYLON.GUI {
         _draw(parentMeasure: Measure, context: CanvasRenderingContext2D): void;
         _measure(): void;
         protected _computeAlignment(parentMeasure: Measure, context: CanvasRenderingContext2D): void;
-        _moveToProjectedPosition(projectedPosition: Vector3): void;
+        /**
+         * Move one end of the line given 3D cartesian coordinates.
+         * @param position Targeted world position
+         * @param scene Scene
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        moveToVector3(position: Vector3, scene: Scene, end?: boolean): void;
+        /**
+         * Move one end of the line to a position in screen absolute space.
+         * @param projectedPosition Position in screen absolute space (X, Y)
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        _moveToProjectedPosition(projectedPosition: Vector3, end?: boolean): void;
     }
 }
 

+ 1 - 1
dist/preview release/gui/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-gui",
     "description": "The Babylon.js GUI library is an extension you can use to generate interactive user interface. It is build on top of the DynamicTexture.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 1 - 1
dist/preview release/inspector/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-inspector",
     "description": "The Babylon.js inspector.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 49 - 22
dist/preview release/loaders/babylon.glTF1FileLoader.d.ts

@@ -28,6 +28,17 @@ declare module BABYLON {
         json: Object;
         bin: Nullable<ArrayBufferView>;
     }
+    enum GLTFLoaderState {
+        Loading = 0,
+        Ready = 1,
+        Complete = 2,
+    }
+    interface IGLTFLoaderExtension {
+        enabled: boolean;
+    }
+    interface IGLTFLoaderExtensions {
+        [name: string]: IGLTFLoaderExtension;
+    }
     interface IGLTFLoader extends IDisposable {
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
@@ -39,8 +50,14 @@ declare module BABYLON {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
-        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
+        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<void>;
     }
     class GLTFFileLoader implements IDisposable, ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
         static CreateGLTFLoaderV1: () => IGLTFLoader;
@@ -78,19 +95,19 @@ declare module BABYLON {
         /**
          * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
          */
-        onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
         private _onMeshLoadedObserver;
         onMeshLoaded: (mesh: AbstractMesh) => void;
         /**
          * Raised when the loader creates a texture after parsing the glTF properties of the texture.
          */
-        onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
         private _onTextureLoadedObserver;
         onTextureLoaded: (Texture: BaseTexture) => void;
         /**
          * Raised when the loader creates a material after parsing the glTF properties of the material.
          */
-        onMaterialLoadedObservable: Observable<Material>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
         private _onMaterialLoadedObserver;
         onMaterialLoaded: (Material: Material) => void;
         /**
@@ -98,15 +115,23 @@ declare module BABYLON {
          * For assets with LODs, raised when all of the LODs are complete.
          * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
-        onCompleteObservable: Observable<GLTFFileLoader>;
+        readonly onCompleteObservable: Observable<GLTFFileLoader>;
         private _onCompleteObserver;
         onComplete: () => void;
         /**
         * Raised when the loader is disposed.
         */
-        onDisposeObservable: Observable<GLTFFileLoader>;
+        readonly onDisposeObservable: Observable<GLTFFileLoader>;
         private _onDisposeObserver;
         onDispose: () => void;
+        /**
+         * The loader state or null if not active.
+         */
+        readonly loaderState: Nullable<GLTFLoaderState>;
+        /**
+         * The loader extensions or null if not active.
+         */
+        readonly loaderExtensions: Nullable<IGLTFLoaderExtensions>;
         private _loader;
         name: string;
         extensions: ISceneLoaderPluginExtensions;
@@ -114,9 +139,13 @@ declare module BABYLON {
          * Disposes the loader, releases resources during load, and cancels any outstanding requests.
          */
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets: AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
+        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        loadAssetContainerAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
         canDirectLoad(data: string): boolean;
         rewriteRootURL: (rootUrl: string, responseURL?: string) => string;
         createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
@@ -534,9 +563,17 @@ declare module BABYLON.GLTF1 {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): boolean;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): void;
+        private _importMeshAsync(meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError);
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        private _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError);
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<void>;
         private _loadShadersAsync(gltfRuntime, onload);
         private _loadBuffersAsync(gltfRuntime, onLoad, onProgress?);
         private _createNodes(gltfRuntime);
@@ -567,16 +604,6 @@ declare module BABYLON.GLTF1 {
          */
         static SetUniform(shaderMaterial: ShaderMaterial | Effect, uniform: string, value: any, type: number): boolean;
         /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        /**
         * Returns the wrap mode of the texture
         * @param mode: the mode value
         */

+ 93 - 78
dist/preview release/loaders/babylon.glTF1FileLoader.js

@@ -27,6 +27,12 @@ var BABYLON;
          */
         GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
     })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
+    var GLTFLoaderState;
+    (function (GLTFLoaderState) {
+        GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
+        GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
+        GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
+    })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
     var GLTFFileLoader = /** @class */ (function () {
         function GLTFFileLoader() {
             // #region Common options
@@ -148,6 +154,26 @@ var BABYLON;
             enumerable: true,
             configurable: true
         });
+        Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
+            /**
+             * The loader state or null if not active.
+             */
+            get: function () {
+                return this._loader ? this._loader.state : null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GLTFFileLoader.prototype, "loaderExtensions", {
+            /**
+             * The loader extensions or null if not active.
+             */
+            get: function () {
+                return this._loader ? this._loader.extensions : null;
+            },
+            enumerable: true,
+            configurable: true
+        });
         /**
          * Disposes the loader, releases resources during load, and cancels any outstanding requests.
          */
@@ -164,57 +190,36 @@ var BABYLON;
             this.onDisposeObservable.notifyObservers(this);
             this.onDisposeObservable.clear();
         };
-        GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
-            try {
-                var loaderData = this._parse(data);
-                this._loader = this._getLoader(loaderData);
-                this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    BABYLON.Tools.Error(e.message);
-                }
-            }
+        GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
+            var _this = this;
+            return Promise.resolve().then(function () {
+                var loaderData = _this._parse(data);
+                _this._loader = _this._getLoader(loaderData);
+                return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
+            });
         };
-        GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
-            try {
-                var loaderData = this._parse(data);
-                this._loader = this._getLoader(loaderData);
-                this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    BABYLON.Tools.Error(e.message);
-                }
-            }
+        GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
+            var _this = this;
+            return Promise.resolve().then(function () {
+                var loaderData = _this._parse(data);
+                _this._loader = _this._getLoader(loaderData);
+                return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
+            });
         };
-        GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
-            try {
-                var loaderData = this._parse(data);
-                this._loader = this._getLoader(loaderData);
-                this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
+        GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
+            var _this = this;
+            return Promise.resolve().then(function () {
+                var loaderData = _this._parse(data);
+                _this._loader = _this._getLoader(loaderData);
+                return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
                     var container = new BABYLON.AssetContainer(scene);
-                    Array.prototype.push.apply(container.meshes, meshes);
-                    Array.prototype.push.apply(container.particleSystems, particleSystems);
-                    Array.prototype.push.apply(container.skeletons, skeletons);
+                    Array.prototype.push.apply(container.meshes, result.meshes);
+                    Array.prototype.push.apply(container.particleSystems, result.particleSystems);
+                    Array.prototype.push.apply(container.skeletons, result.skeletons);
                     container.removeAllFromScene();
-                    onSuccess(container);
-                }, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    BABYLON.Tools.Error(e.message);
-                }
-            }
+                    return container;
+                });
+            });
         };
         GLTFFileLoader.prototype.canDirectLoad = function (data) {
             return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
@@ -1009,8 +1014,7 @@ var BABYLON;
                 return newMesh;
             }
             var subMaterials = [];
-            var vertexData = new BABYLON.VertexData();
-            var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
+            var vertexData = null;
             var verticesStarts = new Array();
             var verticesCounts = new Array();
             var indexStarts = new Array();
@@ -1094,7 +1098,12 @@ var BABYLON;
                         tempVertexData.indices = new Int32Array(indices);
                         indexCounts.push(tempVertexData.indices.length);
                     }
-                    vertexData.merge(tempVertexData);
+                    if (!vertexData) {
+                        vertexData = tempVertexData;
+                    }
+                    else {
+                        vertexData.merge(tempVertexData);
+                    }
                     // Sub material
                     var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
                     subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
@@ -1118,7 +1127,7 @@ var BABYLON;
                 newMesh.material = material;
             }
             // Apply geometry
-            geometry.setAllVerticesData(vertexData, false);
+            new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
             newMesh.computeWorldMatrix(true);
             // Apply submeshes
             newMesh.subMeshes = [];
@@ -1593,8 +1602,8 @@ var BABYLON;
             };
             GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
                 var buffer = gltfRuntime.buffers[id];
-                if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
-                    setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
+                if (BABYLON.Tools.IsBase64(buffer.uri)) {
+                    setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
                 }
                 else {
                     BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
@@ -1615,8 +1624,8 @@ var BABYLON;
                     return;
                 }
                 var source = gltfRuntime.images[texture.source];
-                if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
-                    setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
+                if (BABYLON.Tools.IsBase64(source.uri)) {
+                    setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
                 }
                 else {
                     BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
@@ -1654,7 +1663,7 @@ var BABYLON;
             };
             GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
                 var shader = gltfRuntime.shaders[id];
-                if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
+                if (BABYLON.Tools.IsBase64(shader.uri)) {
                     var shaderString = atob(shader.uri.split(",")[1]);
                     onSuccess(shaderString);
                 }
@@ -1818,6 +1827,8 @@ var BABYLON;
                 this.onTextureLoadedObservable = new BABYLON.Observable();
                 this.onMaterialLoadedObservable = new BABYLON.Observable();
                 this.onCompleteObservable = new BABYLON.Observable();
+                this.state = null;
+                this.extensions = null;
             }
             GLTFLoader.RegisterExtension = function (extension) {
                 if (GLTFLoader.Extensions[extension.name]) {
@@ -1828,7 +1839,7 @@ var BABYLON;
             };
             GLTFLoader.prototype.dispose = function () { };
             // #endregion
-            GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
+            GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
                 var _this = this;
                 scene.useRightHandedSystem = true;
                 GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
@@ -1879,7 +1890,21 @@ var BABYLON;
                 }, onError);
                 return true;
             };
-            GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
+            GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
+                var _this = this;
+                return new Promise(function (resolve, reject) {
+                    _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
+                        resolve({
+                            meshes: meshes,
+                            particleSystems: particleSystems,
+                            skeletons: skeletons
+                        });
+                    }, onProgress, function (message) {
+                        reject(new Error(message));
+                    });
+                });
+            };
+            GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
                 var _this = this;
                 scene.useRightHandedSystem = true;
                 GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
@@ -1903,6 +1928,16 @@ var BABYLON;
                     }, onError);
                 }, onError);
             };
+            GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
+                var _this = this;
+                return new Promise(function (resolve, reject) {
+                    _this._loadAsync(scene, data, rootUrl, function () {
+                        resolve();
+                    }, onProgress, function (message) {
+                        reject(new Error(message));
+                    });
+                });
+            };
             GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
                 var hasShaders = false;
                 var processShader = function (sha, shader) {
@@ -2094,26 +2129,6 @@ var BABYLON;
                 }
             };
             /**
-            * If the uri is a base64 string
-            * @param uri: the uri to test
-            */
-            GLTFUtils.IsBase64 = function (uri) {
-                return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
-            };
-            /**
-            * Decode the base64 uri
-            * @param uri: the uri to decode
-            */
-            GLTFUtils.DecodeBase64 = function (uri) {
-                var decodedString = atob(uri.split(",")[1]);
-                var bufferLength = decodedString.length;
-                var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
-                for (var i = 0; i < bufferLength; i++) {
-                    bufferView[i] = decodedString.charCodeAt(i);
-                }
-                return bufferView.buffer;
-            };
-            /**
             * Returns the wrap mode of the texture
             * @param mode: the mode value
             */

File diff suppressed because it is too large
+ 2 - 2
dist/preview release/loaders/babylon.glTF1FileLoader.min.js


+ 227 - 382
dist/preview release/loaders/babylon.glTF2FileLoader.d.ts

@@ -28,6 +28,17 @@ declare module BABYLON {
         json: Object;
         bin: Nullable<ArrayBufferView>;
     }
+    enum GLTFLoaderState {
+        Loading = 0,
+        Ready = 1,
+        Complete = 2,
+    }
+    interface IGLTFLoaderExtension {
+        enabled: boolean;
+    }
+    interface IGLTFLoaderExtensions {
+        [name: string]: IGLTFLoaderExtension;
+    }
     interface IGLTFLoader extends IDisposable {
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
@@ -39,8 +50,14 @@ declare module BABYLON {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
-        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
+        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<void>;
     }
     class GLTFFileLoader implements IDisposable, ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
         static CreateGLTFLoaderV1: () => IGLTFLoader;
@@ -78,19 +95,19 @@ declare module BABYLON {
         /**
          * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
          */
-        onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
         private _onMeshLoadedObserver;
         onMeshLoaded: (mesh: AbstractMesh) => void;
         /**
          * Raised when the loader creates a texture after parsing the glTF properties of the texture.
          */
-        onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
         private _onTextureLoadedObserver;
         onTextureLoaded: (Texture: BaseTexture) => void;
         /**
          * Raised when the loader creates a material after parsing the glTF properties of the material.
          */
-        onMaterialLoadedObservable: Observable<Material>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
         private _onMaterialLoadedObserver;
         onMaterialLoaded: (Material: Material) => void;
         /**
@@ -98,15 +115,23 @@ declare module BABYLON {
          * For assets with LODs, raised when all of the LODs are complete.
          * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
-        onCompleteObservable: Observable<GLTFFileLoader>;
+        readonly onCompleteObservable: Observable<GLTFFileLoader>;
         private _onCompleteObserver;
         onComplete: () => void;
         /**
         * Raised when the loader is disposed.
         */
-        onDisposeObservable: Observable<GLTFFileLoader>;
+        readonly onDisposeObservable: Observable<GLTFFileLoader>;
         private _onDisposeObserver;
         onDispose: () => void;
+        /**
+         * The loader state or null if not active.
+         */
+        readonly loaderState: Nullable<GLTFLoaderState>;
+        /**
+         * The loader extensions or null if not active.
+         */
+        readonly loaderExtensions: Nullable<IGLTFLoaderExtensions>;
         private _loader;
         name: string;
         extensions: ISceneLoaderPluginExtensions;
@@ -114,9 +139,13 @@ declare module BABYLON {
          * Disposes the loader, releases resources during load, and cancels any outstanding requests.
          */
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets: AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
+        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        loadAssetContainerAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
         canDirectLoad(data: string): boolean;
         rewriteRootURL: (rootUrl: string, responseURL?: string) => string;
         createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
@@ -133,384 +162,192 @@ declare module BABYLON {
 
 
 declare module BABYLON.GLTF2 {
-    /**
-    * Enums
-    */
-    enum EComponentType {
-        BYTE = 5120,
-        UNSIGNED_BYTE = 5121,
-        SHORT = 5122,
-        UNSIGNED_SHORT = 5123,
-        UNSIGNED_INT = 5125,
-        FLOAT = 5126,
-    }
-    enum EMeshPrimitiveMode {
-        POINTS = 0,
-        LINES = 1,
-        LINE_LOOP = 2,
-        LINE_STRIP = 3,
-        TRIANGLES = 4,
-        TRIANGLE_STRIP = 5,
-        TRIANGLE_FAN = 6,
-    }
-    enum ETextureMagFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-    }
-    enum ETextureMinFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-        NEAREST_MIPMAP_NEAREST = 9984,
-        LINEAR_MIPMAP_NEAREST = 9985,
-        NEAREST_MIPMAP_LINEAR = 9986,
-        LINEAR_MIPMAP_LINEAR = 9987,
-    }
-    enum ETextureWrapMode {
-        CLAMP_TO_EDGE = 33071,
-        MIRRORED_REPEAT = 33648,
-        REPEAT = 10497,
-    }
-    /**
-    * Interfaces
-    */
-    interface IGLTFProperty {
-        extensions?: {
-            [key: string]: any;
-        };
-        extras?: any;
-    }
-    interface IGLTFChildRootProperty extends IGLTFProperty {
-        name?: string;
-    }
-    interface IGLTFAccessorSparseIndices extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-    }
-    interface IGLTFAccessorSparseValues extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-    }
-    interface IGLTFAccessorSparse extends IGLTFProperty {
-        count: number;
-        indices: IGLTFAccessorSparseIndices;
-        values: IGLTFAccessorSparseValues;
-    }
-    interface IGLTFAccessor extends IGLTFChildRootProperty {
-        bufferView?: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-        normalized?: boolean;
-        count: number;
-        type: string;
-        max: number[];
-        min: number[];
-        sparse?: IGLTFAccessorSparse;
-        index: number;
-    }
-    interface IGLTFAnimationChannel extends IGLTFProperty {
-        sampler: number;
-        target: IGLTFAnimationChannelTarget;
-    }
-    interface IGLTFAnimationChannelTarget extends IGLTFProperty {
-        node: number;
-        path: string;
-    }
-    interface IGLTFAnimationSampler extends IGLTFProperty {
-        input: number;
-        interpolation?: string;
-        output: number;
-    }
-    interface IGLTFAnimation extends IGLTFChildRootProperty {
-        channels: IGLTFAnimationChannel[];
-        samplers: IGLTFAnimationSampler[];
-        index: number;
-        babylonAnimationGroup: AnimationGroup;
-    }
-    interface IGLTFAsset extends IGLTFChildRootProperty {
-        copyright?: string;
-        generator?: string;
-        version: string;
-        minVersion?: string;
-    }
-    interface IGLTFBuffer extends IGLTFChildRootProperty {
-        uri?: string;
-        byteLength: number;
-        index: number;
-        loadedData?: ArrayBufferView;
-        loadedObservable?: Observable<IGLTFBuffer>;
-    }
-    interface IGLTFBufferView extends IGLTFChildRootProperty {
-        buffer: number;
-        byteOffset?: number;
-        byteLength: number;
-        byteStride?: number;
-        index: number;
-    }
-    interface IGLTFCameraOrthographic extends IGLTFProperty {
-        xmag: number;
-        ymag: number;
-        zfar: number;
-        znear: number;
-    }
-    interface IGLTFCameraPerspective extends IGLTFProperty {
-        aspectRatio: number;
-        yfov: number;
-        zfar: number;
-        znear: number;
-    }
-    interface IGLTFCamera extends IGLTFChildRootProperty {
-        orthographic?: IGLTFCameraOrthographic;
-        perspective?: IGLTFCameraPerspective;
-        type: string;
-    }
-    interface IGLTFImage extends IGLTFChildRootProperty {
-        uri?: string;
-        mimeType?: string;
-        bufferView?: number;
-        index: number;
-    }
-    interface IGLTFMaterialNormalTextureInfo extends IGLTFTextureInfo {
-        scale: number;
-    }
-    interface IGLTFMaterialOcclusionTextureInfo extends IGLTFTextureInfo {
-        strength: number;
-    }
-    interface IGLTFMaterialPbrMetallicRoughness {
-        baseColorFactor: number[];
-        baseColorTexture: IGLTFTextureInfo;
-        metallicFactor: number;
-        roughnessFactor: number;
-        metallicRoughnessTexture: IGLTFTextureInfo;
-    }
-    interface IGLTFMaterial extends IGLTFChildRootProperty {
-        pbrMetallicRoughness?: IGLTFMaterialPbrMetallicRoughness;
-        normalTexture?: IGLTFMaterialNormalTextureInfo;
-        occlusionTexture?: IGLTFMaterialOcclusionTextureInfo;
-        emissiveTexture?: IGLTFTextureInfo;
-        emissiveFactor?: number[];
-        alphaMode?: string;
-        alphaCutoff: number;
-        doubleSided?: boolean;
-        index: number;
-        babylonMaterial: Material;
-    }
-    interface IGLTFMeshPrimitive extends IGLTFProperty {
-        attributes: {
-            [name: string]: number;
-        };
-        indices?: number;
-        material?: number;
-        mode?: EMeshPrimitiveMode;
-        targets?: {
-            [name: string]: number;
-        }[];
-        vertexData: VertexData;
-        targetsVertexData: VertexData[];
-    }
-    interface IGLTFMesh extends IGLTFChildRootProperty {
-        primitives: IGLTFMeshPrimitive[];
-        weights?: number[];
-        index: number;
-        hasVertexAlpha: boolean;
-    }
-    interface IGLTFNode extends IGLTFChildRootProperty {
-        camera?: number;
-        children?: number[];
-        skin?: number;
-        matrix?: number[];
-        mesh?: number;
-        rotation?: number[];
-        scale?: number[];
-        translation?: number[];
-        weights?: number[];
-        index: number;
-        parent: IGLTFNode;
-        babylonMesh: Mesh;
-        babylonAnimationTargets?: Node[];
-    }
-    interface IGLTFSampler extends IGLTFChildRootProperty {
-        magFilter?: ETextureMagFilter;
-        minFilter?: ETextureMinFilter;
-        wrapS?: ETextureWrapMode;
-        wrapT?: ETextureWrapMode;
-        index: number;
+    interface TypedArray extends ArrayBufferView {
+        [index: number]: number;
+    }
+    interface IArrayItem {
+        _index: number;
+    }
+    class ArrayItem {
+        static Assign(values?: IArrayItem[]): void;
+    }
+}
+
+
+
+declare module BABYLON.GLTF2 {
+    interface ILoaderAccessor extends IAccessor, IArrayItem {
+        _data?: Promise<TypedArray>;
+    }
+    interface ILoaderAnimationChannel extends IAnimationChannel, IArrayItem {
+        _babylonAnimationGroup: AnimationGroup;
+    }
+    interface ILoaderAnimationSamplerData {
+        input: Float32Array;
+        interpolation: AnimationSamplerInterpolation;
+        output: Float32Array;
+    }
+    interface ILoaderAnimationSampler extends IAnimationSampler, IArrayItem {
+        _data: Promise<ILoaderAnimationSamplerData>;
+    }
+    interface ILoaderAnimation extends IAnimation, IArrayItem {
+        channels: ILoaderAnimationChannel[];
+        samplers: ILoaderAnimationSampler[];
+        _babylonAnimationGroup: Nullable<AnimationGroup>;
+    }
+    interface ILoaderBuffer extends IBuffer, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
+    }
+    interface ILoaderBufferView extends IBufferView, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
+    }
+    interface ILoaderCamera extends ICamera, IArrayItem {
+    }
+    interface ILoaderImage extends IImage, IArrayItem {
+        _objectURL?: Promise<string>;
+    }
+    interface ILoaderMaterial extends IMaterial, IArrayItem {
+        _babylonMaterial?: Material;
+        _babylonMeshes?: AbstractMesh[];
+        _loaded?: Promise<void>;
+    }
+    interface ILoaderMesh extends IMesh, IArrayItem {
+        primitives: ILoaderMeshPrimitive[];
+    }
+    interface ILoaderMeshPrimitive extends IMeshPrimitive, IArrayItem {
+    }
+    interface ILoaderNode extends INode, IArrayItem {
+        _parent: ILoaderNode;
+        _babylonMesh?: Mesh;
+        _primitiveBabylonMeshes?: Mesh[];
+        _babylonAnimationTargets?: Node[];
+        _numMorphTargets?: number;
+    }
+    interface ILoaderSamplerData {
         noMipMaps: boolean;
         samplingMode: number;
         wrapU: number;
         wrapV: number;
     }
-    interface IGLTFScene extends IGLTFChildRootProperty {
-        nodes: number[];
-        index: number;
-    }
-    interface IGLTFSkin extends IGLTFChildRootProperty {
-        inverseBindMatrices?: number;
-        skeleton?: number;
-        joints: number[];
-        index: number;
-        babylonSkeleton: Skeleton;
-    }
-    interface IGLTFTexture extends IGLTFChildRootProperty {
-        sampler?: number;
-        source: number;
-        index: number;
-        url?: string;
-        dataReadyObservable?: Observable<IGLTFTexture>;
-    }
-    interface IGLTFTextureInfo {
-        index: number;
-        texCoord?: number;
-    }
-    interface _IGLTF extends IGLTFProperty {
-        accessors?: IGLTFAccessor[];
-        animations?: IGLTFAnimation[];
-        asset: IGLTFAsset;
-        buffers?: IGLTFBuffer[];
-        bufferViews?: IGLTFBufferView[];
-        cameras?: IGLTFCamera[];
-        extensionsUsed?: string[];
-        extensionsRequired?: string[];
-        images?: IGLTFImage[];
-        materials?: IGLTFMaterial[];
-        meshes?: IGLTFMesh[];
-        nodes?: IGLTFNode[];
-        samplers?: IGLTFSampler[];
-        scene?: number;
-        scenes?: IGLTFScene[];
-        skins?: IGLTFSkin[];
-        textures?: IGLTFTexture[];
+    interface ILoaderSampler extends ISampler, IArrayItem {
+        _data?: ILoaderSamplerData;
+    }
+    interface ILoaderScene extends IScene, IArrayItem {
+    }
+    interface ILoaderSkin extends ISkin, IArrayItem {
+        _babylonSkeleton: Nullable<Skeleton>;
+        _loaded?: Promise<void>;
+    }
+    interface ILoaderTexture extends ITexture, IArrayItem {
+    }
+    interface ILoaderGLTF extends IGLTF {
+        accessors?: ILoaderAccessor[];
+        animations?: ILoaderAnimation[];
+        buffers?: ILoaderBuffer[];
+        bufferViews?: ILoaderBufferView[];
+        cameras?: ILoaderCamera[];
+        images?: ILoaderImage[];
+        materials?: ILoaderMaterial[];
+        meshes?: ILoaderMesh[];
+        nodes?: ILoaderNode[];
+        samplers?: ILoaderSampler[];
+        scenes?: ILoaderScene[];
+        skins?: ILoaderSkin[];
+        textures?: ILoaderTexture[];
     }
 }
 
 
 declare module BABYLON.GLTF2 {
     class GLTFLoader implements IGLTFLoader {
-        _gltf: _IGLTF;
+        _gltf: ILoaderGLTF;
         _babylonScene: Scene;
+        _completePromises: Promise<void>[];
         private _disposed;
+        private _state;
+        private _extensions;
         private _rootUrl;
-        private _defaultMaterial;
+        private _rootBabylonMesh;
         private _defaultSampler;
-        private _rootNode;
-        private _successCallback?;
         private _progressCallback?;
-        private _errorCallback?;
-        private _renderReady;
         private _requests;
-        private _renderReadyObservable;
-        private _renderPendingCount;
-        private _loaderPendingCount;
-        private _loaderTrackers;
-        static Extensions: {
-            [name: string]: GLTFLoaderExtension;
-        };
-        static RegisterExtension(extension: GLTFLoaderExtension): void;
+        private static _Names;
+        private static _Factories;
+        static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void;
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
         compileMaterials: boolean;
         useClipPlane: boolean;
         compileShadowGenerators: boolean;
-        onDisposeObservable: Observable<IGLTFLoader>;
-        onMeshLoadedObservable: Observable<AbstractMesh>;
-        onTextureLoadedObservable: Observable<BaseTexture>;
-        onMaterialLoadedObservable: Observable<Material>;
-        onCompleteObservable: Observable<IGLTFLoader>;
+        readonly onDisposeObservable: Observable<IGLTFLoader>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
+        readonly onCompleteObservable: Observable<IGLTFLoader>;
+        readonly state: Nullable<GLTFLoaderState>;
+        readonly extensions: IGLTFLoaderExtensions;
+        constructor();
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        private _loadAsync(nodeNames, scene, data, rootUrl, onSuccess?, onProgress?, onError?);
-        private _onProgress();
-        _executeWhenRenderReady(func: () => void): void;
-        private _onRenderReady();
-        private _onComplete();
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        private _loadAsync(nodes, scene, data, rootUrl, onProgress?);
         private _loadData(data);
+        private _setupData();
+        private _createRootNode();
+        private _loadNodesAsync(nodes);
+        _loadSceneAsync(context: string, scene: ILoaderScene): Promise<void>;
         private _getMeshes();
         private _getSkeletons();
         private _startAnimations();
-        private _loadDefaultScene(nodeNames);
-        private _loadScene(context, scene, nodeNames);
-        _loadNode(context: string, node: IGLTFNode): void;
-        private _loadMesh(context, node, mesh);
-        private _loadAllVertexDataAsync(context, mesh, onSuccess);
-        /**
-         * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4TextureCoordArray(context, data, accessor);
-        /**
-         * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4ColorArray(context, data, accessor);
-        private _loadVertexDataAsync(context, mesh, primitive, onSuccess);
-        private _createMorphTargets(context, node, mesh);
-        private _loadMorphTargets(context, node, mesh);
-        private _loadAllMorphTargetVertexDataAsync(context, node, mesh, onSuccess);
-        private _loadMorphTargetVertexDataAsync(context, vertexData, attributes, onSuccess);
-        private _loadTransform(node);
-        private _loadSkinAsync(context, skin, onSuccess);
+        _loadNodeAsync(context: string, node: ILoaderNode): Promise<void>;
+        private _loadMeshAsync(context, node, mesh);
+        private _loadPrimitiveAsync(context, node, mesh, primitive);
+        private _loadVertexDataAsync(context, primitive, babylonMesh);
+        private _createMorphTargets(context, node, mesh, primitive, babylonMesh);
+        private _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
+        private _loadMorphTargetVertexDataAsync(context, babylonVertexData, attributes, babylonMorphTarget);
+        private static _ConvertToFloat32Array(context, accessor, data);
+        private static _ConvertVec3ToVec4(context, data);
+        private static _LoadTransform(node, babylonNode);
+        private _loadSkinAsync(context, node, mesh, skin);
+        private _loadSkinInverseBindMatricesDataAsync(context, skin);
         private _createBone(node, skin, parent, localMatrix, baseMatrix, index);
-        private _loadBones(context, skin, inverseBindMatrixData);
-        private _loadBone(node, skin, inverseBindMatrixData, babylonBones);
+        private _loadBones(context, skin, inverseBindMatricesData);
+        private _loadBone(node, skin, inverseBindMatricesData, babylonBones);
         private _getNodeMatrix(node);
-        private _traverseNodes(context, indices, action, parentNode);
-        _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void;
-        private _loadAnimations();
-        private _loadAnimation(context, animation);
-        private _loadAnimationChannel(animation, channelContext, channel, samplerContext, sampler);
-        private _loadBufferAsync(context, buffer, onSuccess);
-        private _loadBufferViewAsync(context, bufferView, onSuccess);
-        private _loadAccessorAsync(context, accessor, onSuccess);
+        private _loadAnimationsAsync();
+        private _loadAnimationAsync(context, animation);
+        private _loadAnimationChannelAsync(context, animationContext, animation, channel, babylonAnimationGroup);
+        private _loadAnimationSamplerAsync(context, sampler);
+        private _loadBufferAsync(context, buffer);
+        private _loadBufferViewAsync(context, bufferView);
+        private _loadAccessorAsync(context, accessor);
         private _buildArrayBuffer<T>(typedArray, data, byteOffset, count, numComponents, byteStride?);
-        _addPendingData(data: any): void;
-        _removePendingData(data: any): void;
-        _addLoaderPendingData(data: any): void;
-        _removeLoaderPendingData(data: any): void;
-        _whenAction(action: () => void, onComplete: () => void): void;
         private _getDefaultMaterial();
-        private _loadMaterialMetallicRoughnessProperties(context, material);
-        _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void;
-        _createPbrMaterial(material: IGLTFMaterial): void;
-        _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void;
-        _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void;
-        _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex?: number): Texture;
+        private _loadMaterialMetallicRoughnessPropertiesAsync(context, material);
+        _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Promise<void>;
+        _createMaterial(material: ILoaderMaterial): PBRMaterial;
+        _loadMaterialBasePropertiesAsync(context: string, material: ILoaderMaterial): Promise<void>;
+        _loadMaterialAlphaProperties(context: string, material: ILoaderMaterial): void;
+        _loadTextureAsync(context: string, textureInfo: ITextureInfo, assign: (texture: Texture) => void): Promise<void>;
         private _loadSampler(context, sampler);
-        private _loadImageAsync(context, image, onSuccess);
-        _loadUriAsync(context: string, uri: string, onSuccess: (data: ArrayBufferView) => void): void;
-        _tryCatchOnError(handler: () => void): void;
-        private static _AssignIndices(array?);
-        static _GetProperty<T extends IGLTFProperty>(array?: ArrayLike<T>, index?: number): Nullable<T>;
-        private static _GetTextureWrapMode(context, mode?);
+        private _loadImageAsync(context, image);
+        _loadUriAsync(context: string, uri: string): Promise<ArrayBufferView>;
+        private _onProgress();
+        static _GetProperty<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T;
+        private static _GetTextureWrapMode(context, mode);
         private static _GetTextureSamplingMode(context, magFilter?, minFilter?);
         private static _GetNumComponents(context, type);
-        private _compileMaterialAsync(babylonMaterial, babylonMesh, onSuccess);
-        private _compileMaterialsAsync(onSuccess);
-        private _compileShadowGeneratorsAsync(onSuccess);
+        private static _ValidateUri(uri);
+        private _compileMaterialsAsync();
+        private _compileShadowGeneratorsAsync();
         private _abortRequests();
         private _releaseResources();
-    }
-}
-
-
-declare module BABYLON.GLTF2 {
-    /**
-    * Utils functions for GLTF
-    */
-    class GLTFUtils {
-        /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        static ValidateUri(uri: string): boolean;
+        _applyExtensions<T>(actionAsync: (extension: GLTFLoaderExtension) => Nullable<Promise<T>>): Nullable<Promise<T>>;
     }
 }
 
@@ -518,55 +355,63 @@ declare module BABYLON.GLTF2 {
 declare module BABYLON.GLTF2 {
     abstract class GLTFLoaderExtension {
         enabled: boolean;
-        readonly abstract name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        protected _loadExtension<T>(context: string, property: IGLTFProperty, action: (context: string, extension: T, onComplete: () => void) => void): boolean;
-        static _Extensions: GLTFLoaderExtension[];
-        static TraverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        static LoadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        static LoadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        static LoadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        static LoadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private static _ApplyExtensions(action);
+        protected _loader: GLTFLoader;
+        constructor(loader: GLTFLoader);
+        protected readonly abstract _name: string;
+        /** Override this method to modify the default behavior for loading scenes. */
+        protected _loadSceneAsync(context: string, node: ILoaderScene): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading nodes. */
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading materials. */
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading uris. */
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
+        /** Helper method called by a loader extension to load an glTF extension. */
+        protected _loadExtensionAsync<T>(context: string, property: IProperty, actionAsync: (context: string, extension: T) => Promise<void>): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading scenes. */
+        static _LoadSceneAsync(loader: GLTFLoader, context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading nodes. */
+        static _LoadNodeAsync(loader: GLTFLoader, context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading materials. */
+        static _LoadMaterialAsync(loader: GLTFLoader, context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading uris. */
+        static _LoadUriAsync(loader: GLTFLoader, context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class MSFTLOD extends GLTFLoaderExtension {
+        private _loadingNodeLOD;
+        private _loadNodeSignals;
+        private _loadingMaterialLOD;
+        private _loadMaterialSignals;
+        protected readonly _name: string;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
         /**
-         * Specify the minimal delay between LODs in ms (default = 250)
+         * Gets an array of LOD properties from lowest to highest.
          */
-        Delay: number;
-        readonly name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        private _loadNodeLOD(loader, context, nodes, index, onComplete);
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadMaterialLOD(loader, context, materials, index, assign, onComplete);
+        private static _GetLODs<T>(context, property, array, ids);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRMaterialsPbrSpecularGlossiness extends GLTFLoaderExtension {
-        readonly name: string;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadSpecularGlossinessProperties(loader, context, material, properties);
+        protected readonly _name: string;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        private _loadSpecularGlossinessPropertiesAsync(loader, context, material, properties);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRLights extends GLTFLoaderExtension {
-        readonly name: string;
-        private applyCommonProperties(light, lightInfo);
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
+        protected readonly _name: string;
+        protected _loadSceneAsync(context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        private readonly _lights;
     }
 }

File diff suppressed because it is too large
+ 1129 - 1494
dist/preview release/loaders/babylon.glTF2FileLoader.js


File diff suppressed because it is too large
+ 2 - 2
dist/preview release/loaders/babylon.glTF2FileLoader.min.js


+ 220 - 377
dist/preview release/loaders/babylon.glTFFileLoader.d.ts

@@ -28,6 +28,17 @@ declare module BABYLON {
         json: Object;
         bin: Nullable<ArrayBufferView>;
     }
+    enum GLTFLoaderState {
+        Loading = 0,
+        Ready = 1,
+        Complete = 2,
+    }
+    interface IGLTFLoaderExtension {
+        enabled: boolean;
+    }
+    interface IGLTFLoaderExtensions {
+        [name: string]: IGLTFLoaderExtension;
+    }
     interface IGLTFLoader extends IDisposable {
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
@@ -39,8 +50,14 @@ declare module BABYLON {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
-        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
+        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<void>;
     }
     class GLTFFileLoader implements IDisposable, ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
         static CreateGLTFLoaderV1: () => IGLTFLoader;
@@ -78,19 +95,19 @@ declare module BABYLON {
         /**
          * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
          */
-        onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
         private _onMeshLoadedObserver;
         onMeshLoaded: (mesh: AbstractMesh) => void;
         /**
          * Raised when the loader creates a texture after parsing the glTF properties of the texture.
          */
-        onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
         private _onTextureLoadedObserver;
         onTextureLoaded: (Texture: BaseTexture) => void;
         /**
          * Raised when the loader creates a material after parsing the glTF properties of the material.
          */
-        onMaterialLoadedObservable: Observable<Material>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
         private _onMaterialLoadedObserver;
         onMaterialLoaded: (Material: Material) => void;
         /**
@@ -98,15 +115,23 @@ declare module BABYLON {
          * For assets with LODs, raised when all of the LODs are complete.
          * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
-        onCompleteObservable: Observable<GLTFFileLoader>;
+        readonly onCompleteObservable: Observable<GLTFFileLoader>;
         private _onCompleteObserver;
         onComplete: () => void;
         /**
         * Raised when the loader is disposed.
         */
-        onDisposeObservable: Observable<GLTFFileLoader>;
+        readonly onDisposeObservable: Observable<GLTFFileLoader>;
         private _onDisposeObserver;
         onDispose: () => void;
+        /**
+         * The loader state or null if not active.
+         */
+        readonly loaderState: Nullable<GLTFLoaderState>;
+        /**
+         * The loader extensions or null if not active.
+         */
+        readonly loaderExtensions: Nullable<IGLTFLoaderExtensions>;
         private _loader;
         name: string;
         extensions: ISceneLoaderPluginExtensions;
@@ -114,9 +139,13 @@ declare module BABYLON {
          * Disposes the loader, releases resources during load, and cancels any outstanding requests.
          */
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets: AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
+        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        loadAssetContainerAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
         canDirectLoad(data: string): boolean;
         rewriteRootURL: (rootUrl: string, responseURL?: string) => string;
         createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
@@ -534,9 +563,17 @@ declare module BABYLON.GLTF1 {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): boolean;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): void;
+        private _importMeshAsync(meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError);
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        private _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError);
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<void>;
         private _loadShadersAsync(gltfRuntime, onload);
         private _loadBuffersAsync(gltfRuntime, onLoad, onProgress?);
         private _createNodes(gltfRuntime);
@@ -567,16 +604,6 @@ declare module BABYLON.GLTF1 {
          */
         static SetUniform(shaderMaterial: ShaderMaterial | Effect, uniform: string, value: any, type: number): boolean;
         /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        /**
         * Returns the wrap mode of the texture
         * @param mode: the mode value
         */
@@ -690,384 +717,192 @@ declare module BABYLON.GLTF1 {
 
 
 declare module BABYLON.GLTF2 {
-    /**
-    * Enums
-    */
-    enum EComponentType {
-        BYTE = 5120,
-        UNSIGNED_BYTE = 5121,
-        SHORT = 5122,
-        UNSIGNED_SHORT = 5123,
-        UNSIGNED_INT = 5125,
-        FLOAT = 5126,
-    }
-    enum EMeshPrimitiveMode {
-        POINTS = 0,
-        LINES = 1,
-        LINE_LOOP = 2,
-        LINE_STRIP = 3,
-        TRIANGLES = 4,
-        TRIANGLE_STRIP = 5,
-        TRIANGLE_FAN = 6,
-    }
-    enum ETextureMagFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-    }
-    enum ETextureMinFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-        NEAREST_MIPMAP_NEAREST = 9984,
-        LINEAR_MIPMAP_NEAREST = 9985,
-        NEAREST_MIPMAP_LINEAR = 9986,
-        LINEAR_MIPMAP_LINEAR = 9987,
+    interface TypedArray extends ArrayBufferView {
+        [index: number]: number;
     }
-    enum ETextureWrapMode {
-        CLAMP_TO_EDGE = 33071,
-        MIRRORED_REPEAT = 33648,
-        REPEAT = 10497,
-    }
-    /**
-    * Interfaces
-    */
-    interface IGLTFProperty {
-        extensions?: {
-            [key: string]: any;
-        };
-        extras?: any;
-    }
-    interface IGLTFChildRootProperty extends IGLTFProperty {
-        name?: string;
-    }
-    interface IGLTFAccessorSparseIndices extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-        componentType: EComponentType;
+    interface IArrayItem {
+        _index: number;
     }
-    interface IGLTFAccessorSparseValues extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
+    class ArrayItem {
+        static Assign(values?: IArrayItem[]): void;
     }
-    interface IGLTFAccessorSparse extends IGLTFProperty {
-        count: number;
-        indices: IGLTFAccessorSparseIndices;
-        values: IGLTFAccessorSparseValues;
-    }
-    interface IGLTFAccessor extends IGLTFChildRootProperty {
-        bufferView?: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-        normalized?: boolean;
-        count: number;
-        type: string;
-        max: number[];
-        min: number[];
-        sparse?: IGLTFAccessorSparse;
-        index: number;
-    }
-    interface IGLTFAnimationChannel extends IGLTFProperty {
-        sampler: number;
-        target: IGLTFAnimationChannelTarget;
-    }
-    interface IGLTFAnimationChannelTarget extends IGLTFProperty {
-        node: number;
-        path: string;
-    }
-    interface IGLTFAnimationSampler extends IGLTFProperty {
-        input: number;
-        interpolation?: string;
-        output: number;
-    }
-    interface IGLTFAnimation extends IGLTFChildRootProperty {
-        channels: IGLTFAnimationChannel[];
-        samplers: IGLTFAnimationSampler[];
-        index: number;
-        babylonAnimationGroup: AnimationGroup;
-    }
-    interface IGLTFAsset extends IGLTFChildRootProperty {
-        copyright?: string;
-        generator?: string;
-        version: string;
-        minVersion?: string;
-    }
-    interface IGLTFBuffer extends IGLTFChildRootProperty {
-        uri?: string;
-        byteLength: number;
-        index: number;
-        loadedData?: ArrayBufferView;
-        loadedObservable?: Observable<IGLTFBuffer>;
+}
+
+
+
+declare module BABYLON.GLTF2 {
+    interface ILoaderAccessor extends IAccessor, IArrayItem {
+        _data?: Promise<TypedArray>;
     }
-    interface IGLTFBufferView extends IGLTFChildRootProperty {
-        buffer: number;
-        byteOffset?: number;
-        byteLength: number;
-        byteStride?: number;
-        index: number;
+    interface ILoaderAnimationChannel extends IAnimationChannel, IArrayItem {
+        _babylonAnimationGroup: AnimationGroup;
     }
-    interface IGLTFCameraOrthographic extends IGLTFProperty {
-        xmag: number;
-        ymag: number;
-        zfar: number;
-        znear: number;
+    interface ILoaderAnimationSamplerData {
+        input: Float32Array;
+        interpolation: AnimationSamplerInterpolation;
+        output: Float32Array;
     }
-    interface IGLTFCameraPerspective extends IGLTFProperty {
-        aspectRatio: number;
-        yfov: number;
-        zfar: number;
-        znear: number;
+    interface ILoaderAnimationSampler extends IAnimationSampler, IArrayItem {
+        _data: Promise<ILoaderAnimationSamplerData>;
     }
-    interface IGLTFCamera extends IGLTFChildRootProperty {
-        orthographic?: IGLTFCameraOrthographic;
-        perspective?: IGLTFCameraPerspective;
-        type: string;
+    interface ILoaderAnimation extends IAnimation, IArrayItem {
+        channels: ILoaderAnimationChannel[];
+        samplers: ILoaderAnimationSampler[];
+        _babylonAnimationGroup: Nullable<AnimationGroup>;
     }
-    interface IGLTFImage extends IGLTFChildRootProperty {
-        uri?: string;
-        mimeType?: string;
-        bufferView?: number;
-        index: number;
+    interface ILoaderBuffer extends IBuffer, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
-    interface IGLTFMaterialNormalTextureInfo extends IGLTFTextureInfo {
-        scale: number;
+    interface ILoaderBufferView extends IBufferView, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
-    interface IGLTFMaterialOcclusionTextureInfo extends IGLTFTextureInfo {
-        strength: number;
+    interface ILoaderCamera extends ICamera, IArrayItem {
     }
-    interface IGLTFMaterialPbrMetallicRoughness {
-        baseColorFactor: number[];
-        baseColorTexture: IGLTFTextureInfo;
-        metallicFactor: number;
-        roughnessFactor: number;
-        metallicRoughnessTexture: IGLTFTextureInfo;
+    interface ILoaderImage extends IImage, IArrayItem {
+        _objectURL?: Promise<string>;
     }
-    interface IGLTFMaterial extends IGLTFChildRootProperty {
-        pbrMetallicRoughness?: IGLTFMaterialPbrMetallicRoughness;
-        normalTexture?: IGLTFMaterialNormalTextureInfo;
-        occlusionTexture?: IGLTFMaterialOcclusionTextureInfo;
-        emissiveTexture?: IGLTFTextureInfo;
-        emissiveFactor?: number[];
-        alphaMode?: string;
-        alphaCutoff: number;
-        doubleSided?: boolean;
-        index: number;
-        babylonMaterial: Material;
+    interface ILoaderMaterial extends IMaterial, IArrayItem {
+        _babylonMaterial?: Material;
+        _babylonMeshes?: AbstractMesh[];
+        _loaded?: Promise<void>;
     }
-    interface IGLTFMeshPrimitive extends IGLTFProperty {
-        attributes: {
-            [name: string]: number;
-        };
-        indices?: number;
-        material?: number;
-        mode?: EMeshPrimitiveMode;
-        targets?: {
-            [name: string]: number;
-        }[];
-        vertexData: VertexData;
-        targetsVertexData: VertexData[];
+    interface ILoaderMesh extends IMesh, IArrayItem {
+        primitives: ILoaderMeshPrimitive[];
     }
-    interface IGLTFMesh extends IGLTFChildRootProperty {
-        primitives: IGLTFMeshPrimitive[];
-        weights?: number[];
-        index: number;
-        hasVertexAlpha: boolean;
+    interface ILoaderMeshPrimitive extends IMeshPrimitive, IArrayItem {
     }
-    interface IGLTFNode extends IGLTFChildRootProperty {
-        camera?: number;
-        children?: number[];
-        skin?: number;
-        matrix?: number[];
-        mesh?: number;
-        rotation?: number[];
-        scale?: number[];
-        translation?: number[];
-        weights?: number[];
-        index: number;
-        parent: IGLTFNode;
-        babylonMesh: Mesh;
-        babylonAnimationTargets?: Node[];
+    interface ILoaderNode extends INode, IArrayItem {
+        _parent: ILoaderNode;
+        _babylonMesh?: Mesh;
+        _primitiveBabylonMeshes?: Mesh[];
+        _babylonAnimationTargets?: Node[];
+        _numMorphTargets?: number;
     }
-    interface IGLTFSampler extends IGLTFChildRootProperty {
-        magFilter?: ETextureMagFilter;
-        minFilter?: ETextureMinFilter;
-        wrapS?: ETextureWrapMode;
-        wrapT?: ETextureWrapMode;
-        index: number;
+    interface ILoaderSamplerData {
         noMipMaps: boolean;
         samplingMode: number;
         wrapU: number;
         wrapV: number;
     }
-    interface IGLTFScene extends IGLTFChildRootProperty {
-        nodes: number[];
-        index: number;
+    interface ILoaderSampler extends ISampler, IArrayItem {
+        _data?: ILoaderSamplerData;
     }
-    interface IGLTFSkin extends IGLTFChildRootProperty {
-        inverseBindMatrices?: number;
-        skeleton?: number;
-        joints: number[];
-        index: number;
-        babylonSkeleton: Skeleton;
+    interface ILoaderScene extends IScene, IArrayItem {
     }
-    interface IGLTFTexture extends IGLTFChildRootProperty {
-        sampler?: number;
-        source: number;
-        index: number;
-        url?: string;
-        dataReadyObservable?: Observable<IGLTFTexture>;
-    }
-    interface IGLTFTextureInfo {
-        index: number;
-        texCoord?: number;
-    }
-    interface _IGLTF extends IGLTFProperty {
-        accessors?: IGLTFAccessor[];
-        animations?: IGLTFAnimation[];
-        asset: IGLTFAsset;
-        buffers?: IGLTFBuffer[];
-        bufferViews?: IGLTFBufferView[];
-        cameras?: IGLTFCamera[];
-        extensionsUsed?: string[];
-        extensionsRequired?: string[];
-        images?: IGLTFImage[];
-        materials?: IGLTFMaterial[];
-        meshes?: IGLTFMesh[];
-        nodes?: IGLTFNode[];
-        samplers?: IGLTFSampler[];
-        scene?: number;
-        scenes?: IGLTFScene[];
-        skins?: IGLTFSkin[];
-        textures?: IGLTFTexture[];
+    interface ILoaderSkin extends ISkin, IArrayItem {
+        _babylonSkeleton: Nullable<Skeleton>;
+        _loaded?: Promise<void>;
+    }
+    interface ILoaderTexture extends ITexture, IArrayItem {
+    }
+    interface ILoaderGLTF extends IGLTF {
+        accessors?: ILoaderAccessor[];
+        animations?: ILoaderAnimation[];
+        buffers?: ILoaderBuffer[];
+        bufferViews?: ILoaderBufferView[];
+        cameras?: ILoaderCamera[];
+        images?: ILoaderImage[];
+        materials?: ILoaderMaterial[];
+        meshes?: ILoaderMesh[];
+        nodes?: ILoaderNode[];
+        samplers?: ILoaderSampler[];
+        scenes?: ILoaderScene[];
+        skins?: ILoaderSkin[];
+        textures?: ILoaderTexture[];
     }
 }
 
 
 declare module BABYLON.GLTF2 {
     class GLTFLoader implements IGLTFLoader {
-        _gltf: _IGLTF;
+        _gltf: ILoaderGLTF;
         _babylonScene: Scene;
+        _completePromises: Promise<void>[];
         private _disposed;
+        private _state;
+        private _extensions;
         private _rootUrl;
-        private _defaultMaterial;
+        private _rootBabylonMesh;
         private _defaultSampler;
-        private _rootNode;
-        private _successCallback?;
         private _progressCallback?;
-        private _errorCallback?;
-        private _renderReady;
         private _requests;
-        private _renderReadyObservable;
-        private _renderPendingCount;
-        private _loaderPendingCount;
-        private _loaderTrackers;
-        static Extensions: {
-            [name: string]: GLTFLoaderExtension;
-        };
-        static RegisterExtension(extension: GLTFLoaderExtension): void;
+        private static _Names;
+        private static _Factories;
+        static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void;
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
         compileMaterials: boolean;
         useClipPlane: boolean;
         compileShadowGenerators: boolean;
-        onDisposeObservable: Observable<IGLTFLoader>;
-        onMeshLoadedObservable: Observable<AbstractMesh>;
-        onTextureLoadedObservable: Observable<BaseTexture>;
-        onMaterialLoadedObservable: Observable<Material>;
-        onCompleteObservable: Observable<IGLTFLoader>;
+        readonly onDisposeObservable: Observable<IGLTFLoader>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
+        readonly onCompleteObservable: Observable<IGLTFLoader>;
+        readonly state: Nullable<GLTFLoaderState>;
+        readonly extensions: IGLTFLoaderExtensions;
+        constructor();
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        private _loadAsync(nodeNames, scene, data, rootUrl, onSuccess?, onProgress?, onError?);
-        private _onProgress();
-        _executeWhenRenderReady(func: () => void): void;
-        private _onRenderReady();
-        private _onComplete();
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        private _loadAsync(nodes, scene, data, rootUrl, onProgress?);
         private _loadData(data);
+        private _setupData();
+        private _createRootNode();
+        private _loadNodesAsync(nodes);
+        _loadSceneAsync(context: string, scene: ILoaderScene): Promise<void>;
         private _getMeshes();
         private _getSkeletons();
         private _startAnimations();
-        private _loadDefaultScene(nodeNames);
-        private _loadScene(context, scene, nodeNames);
-        _loadNode(context: string, node: IGLTFNode): void;
-        private _loadMesh(context, node, mesh);
-        private _loadAllVertexDataAsync(context, mesh, onSuccess);
-        /**
-         * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4TextureCoordArray(context, data, accessor);
-        /**
-         * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4ColorArray(context, data, accessor);
-        private _loadVertexDataAsync(context, mesh, primitive, onSuccess);
-        private _createMorphTargets(context, node, mesh);
-        private _loadMorphTargets(context, node, mesh);
-        private _loadAllMorphTargetVertexDataAsync(context, node, mesh, onSuccess);
-        private _loadMorphTargetVertexDataAsync(context, vertexData, attributes, onSuccess);
-        private _loadTransform(node);
-        private _loadSkinAsync(context, skin, onSuccess);
+        _loadNodeAsync(context: string, node: ILoaderNode): Promise<void>;
+        private _loadMeshAsync(context, node, mesh);
+        private _loadPrimitiveAsync(context, node, mesh, primitive);
+        private _loadVertexDataAsync(context, primitive, babylonMesh);
+        private _createMorphTargets(context, node, mesh, primitive, babylonMesh);
+        private _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
+        private _loadMorphTargetVertexDataAsync(context, babylonVertexData, attributes, babylonMorphTarget);
+        private static _ConvertToFloat32Array(context, accessor, data);
+        private static _ConvertVec3ToVec4(context, data);
+        private static _LoadTransform(node, babylonNode);
+        private _loadSkinAsync(context, node, mesh, skin);
+        private _loadSkinInverseBindMatricesDataAsync(context, skin);
         private _createBone(node, skin, parent, localMatrix, baseMatrix, index);
-        private _loadBones(context, skin, inverseBindMatrixData);
-        private _loadBone(node, skin, inverseBindMatrixData, babylonBones);
+        private _loadBones(context, skin, inverseBindMatricesData);
+        private _loadBone(node, skin, inverseBindMatricesData, babylonBones);
         private _getNodeMatrix(node);
-        private _traverseNodes(context, indices, action, parentNode);
-        _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void;
-        private _loadAnimations();
-        private _loadAnimation(context, animation);
-        private _loadAnimationChannel(animation, channelContext, channel, samplerContext, sampler);
-        private _loadBufferAsync(context, buffer, onSuccess);
-        private _loadBufferViewAsync(context, bufferView, onSuccess);
-        private _loadAccessorAsync(context, accessor, onSuccess);
+        private _loadAnimationsAsync();
+        private _loadAnimationAsync(context, animation);
+        private _loadAnimationChannelAsync(context, animationContext, animation, channel, babylonAnimationGroup);
+        private _loadAnimationSamplerAsync(context, sampler);
+        private _loadBufferAsync(context, buffer);
+        private _loadBufferViewAsync(context, bufferView);
+        private _loadAccessorAsync(context, accessor);
         private _buildArrayBuffer<T>(typedArray, data, byteOffset, count, numComponents, byteStride?);
-        _addPendingData(data: any): void;
-        _removePendingData(data: any): void;
-        _addLoaderPendingData(data: any): void;
-        _removeLoaderPendingData(data: any): void;
-        _whenAction(action: () => void, onComplete: () => void): void;
         private _getDefaultMaterial();
-        private _loadMaterialMetallicRoughnessProperties(context, material);
-        _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void;
-        _createPbrMaterial(material: IGLTFMaterial): void;
-        _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void;
-        _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void;
-        _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex?: number): Texture;
+        private _loadMaterialMetallicRoughnessPropertiesAsync(context, material);
+        _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Promise<void>;
+        _createMaterial(material: ILoaderMaterial): PBRMaterial;
+        _loadMaterialBasePropertiesAsync(context: string, material: ILoaderMaterial): Promise<void>;
+        _loadMaterialAlphaProperties(context: string, material: ILoaderMaterial): void;
+        _loadTextureAsync(context: string, textureInfo: ITextureInfo, assign: (texture: Texture) => void): Promise<void>;
         private _loadSampler(context, sampler);
-        private _loadImageAsync(context, image, onSuccess);
-        _loadUriAsync(context: string, uri: string, onSuccess: (data: ArrayBufferView) => void): void;
-        _tryCatchOnError(handler: () => void): void;
-        private static _AssignIndices(array?);
-        static _GetProperty<T extends IGLTFProperty>(array?: ArrayLike<T>, index?: number): Nullable<T>;
-        private static _GetTextureWrapMode(context, mode?);
+        private _loadImageAsync(context, image);
+        _loadUriAsync(context: string, uri: string): Promise<ArrayBufferView>;
+        private _onProgress();
+        static _GetProperty<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T;
+        private static _GetTextureWrapMode(context, mode);
         private static _GetTextureSamplingMode(context, magFilter?, minFilter?);
         private static _GetNumComponents(context, type);
-        private _compileMaterialAsync(babylonMaterial, babylonMesh, onSuccess);
-        private _compileMaterialsAsync(onSuccess);
-        private _compileShadowGeneratorsAsync(onSuccess);
+        private static _ValidateUri(uri);
+        private _compileMaterialsAsync();
+        private _compileShadowGeneratorsAsync();
         private _abortRequests();
         private _releaseResources();
-    }
-}
-
-
-declare module BABYLON.GLTF2 {
-    /**
-    * Utils functions for GLTF
-    */
-    class GLTFUtils {
-        /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        static ValidateUri(uri: string): boolean;
+        _applyExtensions<T>(actionAsync: (extension: GLTFLoaderExtension) => Nullable<Promise<T>>): Nullable<Promise<T>>;
     }
 }
 
@@ -1075,55 +910,63 @@ declare module BABYLON.GLTF2 {
 declare module BABYLON.GLTF2 {
     abstract class GLTFLoaderExtension {
         enabled: boolean;
-        readonly abstract name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        protected _loadExtension<T>(context: string, property: IGLTFProperty, action: (context: string, extension: T, onComplete: () => void) => void): boolean;
-        static _Extensions: GLTFLoaderExtension[];
-        static TraverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        static LoadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        static LoadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        static LoadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        static LoadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private static _ApplyExtensions(action);
+        protected _loader: GLTFLoader;
+        constructor(loader: GLTFLoader);
+        protected readonly abstract _name: string;
+        /** Override this method to modify the default behavior for loading scenes. */
+        protected _loadSceneAsync(context: string, node: ILoaderScene): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading nodes. */
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading materials. */
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading uris. */
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
+        /** Helper method called by a loader extension to load an glTF extension. */
+        protected _loadExtensionAsync<T>(context: string, property: IProperty, actionAsync: (context: string, extension: T) => Promise<void>): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading scenes. */
+        static _LoadSceneAsync(loader: GLTFLoader, context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading nodes. */
+        static _LoadNodeAsync(loader: GLTFLoader, context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading materials. */
+        static _LoadMaterialAsync(loader: GLTFLoader, context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading uris. */
+        static _LoadUriAsync(loader: GLTFLoader, context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class MSFTLOD extends GLTFLoaderExtension {
-        /**
-         * Specify the minimal delay between LODs in ms (default = 250)
+        private _loadingNodeLOD;
+        private _loadNodeSignals;
+        private _loadingMaterialLOD;
+        private _loadMaterialSignals;
+        protected readonly _name: string;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
+        /**
+         * Gets an array of LOD properties from lowest to highest.
          */
-        Delay: number;
-        readonly name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        private _loadNodeLOD(loader, context, nodes, index, onComplete);
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadMaterialLOD(loader, context, materials, index, assign, onComplete);
+        private static _GetLODs<T>(context, property, array, ids);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRMaterialsPbrSpecularGlossiness extends GLTFLoaderExtension {
-        readonly name: string;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadSpecularGlossinessProperties(loader, context, material, properties);
+        protected readonly _name: string;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        private _loadSpecularGlossinessPropertiesAsync(loader, context, material, properties);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRLights extends GLTFLoaderExtension {
-        readonly name: string;
-        private applyCommonProperties(light, lightInfo);
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
+        protected readonly _name: string;
+        protected _loadSceneAsync(context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        private readonly _lights;
     }
 }

File diff suppressed because it is too large
+ 1159 - 1514
dist/preview release/loaders/babylon.glTFFileLoader.js


File diff suppressed because it is too large
+ 3 - 3
dist/preview release/loaders/babylon.glTFFileLoader.min.js


+ 1 - 1
dist/preview release/loaders/babylon.objFileLoader.d.ts

@@ -58,7 +58,7 @@ declare module BABYLON {
         private _loadMTL(url, rootUrl, onSuccess);
         importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<ParticleSystem[]>, skeletons: Nullable<Skeleton[]>): boolean;
         load(scene: Scene, data: string, rootUrl: string): boolean;
-        loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer>;
+        loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
         /**
          * Read the OBJ file and create an Array of meshes.
          * Each mesh contains all information given by the OBJ and the MTL file.

+ 4 - 7
dist/preview release/loaders/babylon.objFileLoader.js

@@ -260,14 +260,11 @@ var BABYLON;
             //Get the 3D model
             return this.importMesh(null, scene, data, rootUrl, null, null, null);
         };
-        OBJFileLoader.prototype.loadAssets = function (scene, data, rootUrl, onError) {
+        OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
             var container = new BABYLON.AssetContainer(scene);
-            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
-            if (result) {
-                container.removeAllFromScene();
-                return container;
-            }
-            return null;
+            this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            container.removeAllFromScene();
+            return container;
         };
         /**
          * Read the OBJ file and create an Array of meshes.

File diff suppressed because it is too large
+ 1 - 1
dist/preview release/loaders/babylon.objFileLoader.min.js


+ 1 - 1
dist/preview release/loaders/babylon.stlFileLoader.d.ts

@@ -9,7 +9,7 @@ declare module BABYLON {
         extensions: ISceneLoaderPluginExtensions;
         importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<ParticleSystem[]>, skeletons: Nullable<Skeleton[]>): boolean;
         load(scene: Scene, data: any, rootUrl: string): boolean;
-        loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer>;
+        loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
         private isBinary(data);
         private parseBinary(mesh, data);
         private parseASCII(mesh, solidData);

+ 4 - 7
dist/preview release/loaders/babylon.stlFileLoader.js

@@ -70,14 +70,11 @@ var BABYLON;
             }
             return result;
         };
-        STLFileLoader.prototype.loadAssets = function (scene, data, rootUrl, onError) {
+        STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
             var container = new BABYLON.AssetContainer(scene);
-            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
-            if (result) {
-                container.removeAllFromScene();
-                return container;
-            }
-            return null;
+            this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            container.removeAllFromScene();
+            return container;
         };
         STLFileLoader.prototype.isBinary = function (data) {
             // check if file size is correct for binary stl

File diff suppressed because it is too large
+ 1 - 1
dist/preview release/loaders/babylon.stlFileLoader.min.js


File diff suppressed because it is too large
+ 1175 - 1536
dist/preview release/loaders/babylonjs.loaders.js


File diff suppressed because it is too large
+ 3 - 3
dist/preview release/loaders/babylonjs.loaders.min.js


+ 221 - 378
dist/preview release/loaders/babylonjs.loaders.module.d.ts

@@ -15,7 +15,7 @@ declare module BABYLON {
         extensions: ISceneLoaderPluginExtensions;
         importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<ParticleSystem[]>, skeletons: Nullable<Skeleton[]>): boolean;
         load(scene: Scene, data: any, rootUrl: string): boolean;
-        loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer>;
+        loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
         private isBinary(data);
         private parseBinary(mesh, data);
         private parseASCII(mesh, solidData);
@@ -82,7 +82,7 @@ declare module BABYLON {
         private _loadMTL(url, rootUrl, onSuccess);
         importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<ParticleSystem[]>, skeletons: Nullable<Skeleton[]>): boolean;
         load(scene: Scene, data: string, rootUrl: string): boolean;
-        loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer>;
+        loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
         /**
          * Read the OBJ file and create an Array of meshes.
          * Each mesh contains all information given by the OBJ and the MTL file.
@@ -129,6 +129,17 @@ declare module BABYLON {
         json: Object;
         bin: Nullable<ArrayBufferView>;
     }
+    enum GLTFLoaderState {
+        Loading = 0,
+        Ready = 1,
+        Complete = 2,
+    }
+    interface IGLTFLoaderExtension {
+        enabled: boolean;
+    }
+    interface IGLTFLoaderExtensions {
+        [name: string]: IGLTFLoaderExtension;
+    }
     interface IGLTFLoader extends IDisposable {
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
@@ -140,8 +151,14 @@ declare module BABYLON {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
-        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
+        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<void>;
     }
     class GLTFFileLoader implements IDisposable, ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
         static CreateGLTFLoaderV1: () => IGLTFLoader;
@@ -179,19 +196,19 @@ declare module BABYLON {
         /**
          * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
          */
-        onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
         private _onMeshLoadedObserver;
         onMeshLoaded: (mesh: AbstractMesh) => void;
         /**
          * Raised when the loader creates a texture after parsing the glTF properties of the texture.
          */
-        onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
         private _onTextureLoadedObserver;
         onTextureLoaded: (Texture: BaseTexture) => void;
         /**
          * Raised when the loader creates a material after parsing the glTF properties of the material.
          */
-        onMaterialLoadedObservable: Observable<Material>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
         private _onMaterialLoadedObserver;
         onMaterialLoaded: (Material: Material) => void;
         /**
@@ -199,15 +216,23 @@ declare module BABYLON {
          * For assets with LODs, raised when all of the LODs are complete.
          * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
-        onCompleteObservable: Observable<GLTFFileLoader>;
+        readonly onCompleteObservable: Observable<GLTFFileLoader>;
         private _onCompleteObserver;
         onComplete: () => void;
         /**
         * Raised when the loader is disposed.
         */
-        onDisposeObservable: Observable<GLTFFileLoader>;
+        readonly onDisposeObservable: Observable<GLTFFileLoader>;
         private _onDisposeObserver;
         onDispose: () => void;
+        /**
+         * The loader state or null if not active.
+         */
+        readonly loaderState: Nullable<GLTFLoaderState>;
+        /**
+         * The loader extensions or null if not active.
+         */
+        readonly loaderExtensions: Nullable<IGLTFLoaderExtensions>;
         private _loader;
         name: string;
         extensions: ISceneLoaderPluginExtensions;
@@ -215,9 +240,13 @@ declare module BABYLON {
          * Disposes the loader, releases resources during load, and cancels any outstanding requests.
          */
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets: AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
+        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        loadAssetContainerAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
         canDirectLoad(data: string): boolean;
         rewriteRootURL: (rootUrl: string, responseURL?: string) => string;
         createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
@@ -635,9 +664,17 @@ declare module BABYLON.GLTF1 {
         onTextureLoadedObservable: Observable<BaseTexture>;
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): boolean;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): void;
+        private _importMeshAsync(meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError);
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        private _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError);
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<void>;
         private _loadShadersAsync(gltfRuntime, onload);
         private _loadBuffersAsync(gltfRuntime, onLoad, onProgress?);
         private _createNodes(gltfRuntime);
@@ -668,16 +705,6 @@ declare module BABYLON.GLTF1 {
          */
         static SetUniform(shaderMaterial: ShaderMaterial | Effect, uniform: string, value: any, type: number): boolean;
         /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        /**
         * Returns the wrap mode of the texture
         * @param mode: the mode value
         */
@@ -791,384 +818,192 @@ declare module BABYLON.GLTF1 {
 
 
 declare module BABYLON.GLTF2 {
-    /**
-    * Enums
-    */
-    enum EComponentType {
-        BYTE = 5120,
-        UNSIGNED_BYTE = 5121,
-        SHORT = 5122,
-        UNSIGNED_SHORT = 5123,
-        UNSIGNED_INT = 5125,
-        FLOAT = 5126,
-    }
-    enum EMeshPrimitiveMode {
-        POINTS = 0,
-        LINES = 1,
-        LINE_LOOP = 2,
-        LINE_STRIP = 3,
-        TRIANGLES = 4,
-        TRIANGLE_STRIP = 5,
-        TRIANGLE_FAN = 6,
-    }
-    enum ETextureMagFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-    }
-    enum ETextureMinFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-        NEAREST_MIPMAP_NEAREST = 9984,
-        LINEAR_MIPMAP_NEAREST = 9985,
-        NEAREST_MIPMAP_LINEAR = 9986,
-        LINEAR_MIPMAP_LINEAR = 9987,
+    interface TypedArray extends ArrayBufferView {
+        [index: number]: number;
     }
-    enum ETextureWrapMode {
-        CLAMP_TO_EDGE = 33071,
-        MIRRORED_REPEAT = 33648,
-        REPEAT = 10497,
-    }
-    /**
-    * Interfaces
-    */
-    interface IGLTFProperty {
-        extensions?: {
-            [key: string]: any;
-        };
-        extras?: any;
-    }
-    interface IGLTFChildRootProperty extends IGLTFProperty {
-        name?: string;
-    }
-    interface IGLTFAccessorSparseIndices extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-        componentType: EComponentType;
+    interface IArrayItem {
+        _index: number;
     }
-    interface IGLTFAccessorSparseValues extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
+    class ArrayItem {
+        static Assign(values?: IArrayItem[]): void;
     }
-    interface IGLTFAccessorSparse extends IGLTFProperty {
-        count: number;
-        indices: IGLTFAccessorSparseIndices;
-        values: IGLTFAccessorSparseValues;
-    }
-    interface IGLTFAccessor extends IGLTFChildRootProperty {
-        bufferView?: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-        normalized?: boolean;
-        count: number;
-        type: string;
-        max: number[];
-        min: number[];
-        sparse?: IGLTFAccessorSparse;
-        index: number;
-    }
-    interface IGLTFAnimationChannel extends IGLTFProperty {
-        sampler: number;
-        target: IGLTFAnimationChannelTarget;
-    }
-    interface IGLTFAnimationChannelTarget extends IGLTFProperty {
-        node: number;
-        path: string;
-    }
-    interface IGLTFAnimationSampler extends IGLTFProperty {
-        input: number;
-        interpolation?: string;
-        output: number;
-    }
-    interface IGLTFAnimation extends IGLTFChildRootProperty {
-        channels: IGLTFAnimationChannel[];
-        samplers: IGLTFAnimationSampler[];
-        index: number;
-        babylonAnimationGroup: AnimationGroup;
-    }
-    interface IGLTFAsset extends IGLTFChildRootProperty {
-        copyright?: string;
-        generator?: string;
-        version: string;
-        minVersion?: string;
-    }
-    interface IGLTFBuffer extends IGLTFChildRootProperty {
-        uri?: string;
-        byteLength: number;
-        index: number;
-        loadedData?: ArrayBufferView;
-        loadedObservable?: Observable<IGLTFBuffer>;
+}
+
+
+
+declare module BABYLON.GLTF2 {
+    interface ILoaderAccessor extends IAccessor, IArrayItem {
+        _data?: Promise<TypedArray>;
     }
-    interface IGLTFBufferView extends IGLTFChildRootProperty {
-        buffer: number;
-        byteOffset?: number;
-        byteLength: number;
-        byteStride?: number;
-        index: number;
+    interface ILoaderAnimationChannel extends IAnimationChannel, IArrayItem {
+        _babylonAnimationGroup: AnimationGroup;
     }
-    interface IGLTFCameraOrthographic extends IGLTFProperty {
-        xmag: number;
-        ymag: number;
-        zfar: number;
-        znear: number;
+    interface ILoaderAnimationSamplerData {
+        input: Float32Array;
+        interpolation: AnimationSamplerInterpolation;
+        output: Float32Array;
     }
-    interface IGLTFCameraPerspective extends IGLTFProperty {
-        aspectRatio: number;
-        yfov: number;
-        zfar: number;
-        znear: number;
+    interface ILoaderAnimationSampler extends IAnimationSampler, IArrayItem {
+        _data: Promise<ILoaderAnimationSamplerData>;
     }
-    interface IGLTFCamera extends IGLTFChildRootProperty {
-        orthographic?: IGLTFCameraOrthographic;
-        perspective?: IGLTFCameraPerspective;
-        type: string;
+    interface ILoaderAnimation extends IAnimation, IArrayItem {
+        channels: ILoaderAnimationChannel[];
+        samplers: ILoaderAnimationSampler[];
+        _babylonAnimationGroup: Nullable<AnimationGroup>;
     }
-    interface IGLTFImage extends IGLTFChildRootProperty {
-        uri?: string;
-        mimeType?: string;
-        bufferView?: number;
-        index: number;
+    interface ILoaderBuffer extends IBuffer, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
-    interface IGLTFMaterialNormalTextureInfo extends IGLTFTextureInfo {
-        scale: number;
+    interface ILoaderBufferView extends IBufferView, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
-    interface IGLTFMaterialOcclusionTextureInfo extends IGLTFTextureInfo {
-        strength: number;
+    interface ILoaderCamera extends ICamera, IArrayItem {
     }
-    interface IGLTFMaterialPbrMetallicRoughness {
-        baseColorFactor: number[];
-        baseColorTexture: IGLTFTextureInfo;
-        metallicFactor: number;
-        roughnessFactor: number;
-        metallicRoughnessTexture: IGLTFTextureInfo;
+    interface ILoaderImage extends IImage, IArrayItem {
+        _objectURL?: Promise<string>;
     }
-    interface IGLTFMaterial extends IGLTFChildRootProperty {
-        pbrMetallicRoughness?: IGLTFMaterialPbrMetallicRoughness;
-        normalTexture?: IGLTFMaterialNormalTextureInfo;
-        occlusionTexture?: IGLTFMaterialOcclusionTextureInfo;
-        emissiveTexture?: IGLTFTextureInfo;
-        emissiveFactor?: number[];
-        alphaMode?: string;
-        alphaCutoff: number;
-        doubleSided?: boolean;
-        index: number;
-        babylonMaterial: Material;
+    interface ILoaderMaterial extends IMaterial, IArrayItem {
+        _babylonMaterial?: Material;
+        _babylonMeshes?: AbstractMesh[];
+        _loaded?: Promise<void>;
     }
-    interface IGLTFMeshPrimitive extends IGLTFProperty {
-        attributes: {
-            [name: string]: number;
-        };
-        indices?: number;
-        material?: number;
-        mode?: EMeshPrimitiveMode;
-        targets?: {
-            [name: string]: number;
-        }[];
-        vertexData: VertexData;
-        targetsVertexData: VertexData[];
+    interface ILoaderMesh extends IMesh, IArrayItem {
+        primitives: ILoaderMeshPrimitive[];
     }
-    interface IGLTFMesh extends IGLTFChildRootProperty {
-        primitives: IGLTFMeshPrimitive[];
-        weights?: number[];
-        index: number;
-        hasVertexAlpha: boolean;
+    interface ILoaderMeshPrimitive extends IMeshPrimitive, IArrayItem {
     }
-    interface IGLTFNode extends IGLTFChildRootProperty {
-        camera?: number;
-        children?: number[];
-        skin?: number;
-        matrix?: number[];
-        mesh?: number;
-        rotation?: number[];
-        scale?: number[];
-        translation?: number[];
-        weights?: number[];
-        index: number;
-        parent: IGLTFNode;
-        babylonMesh: Mesh;
-        babylonAnimationTargets?: Node[];
+    interface ILoaderNode extends INode, IArrayItem {
+        _parent: ILoaderNode;
+        _babylonMesh?: Mesh;
+        _primitiveBabylonMeshes?: Mesh[];
+        _babylonAnimationTargets?: Node[];
+        _numMorphTargets?: number;
     }
-    interface IGLTFSampler extends IGLTFChildRootProperty {
-        magFilter?: ETextureMagFilter;
-        minFilter?: ETextureMinFilter;
-        wrapS?: ETextureWrapMode;
-        wrapT?: ETextureWrapMode;
-        index: number;
+    interface ILoaderSamplerData {
         noMipMaps: boolean;
         samplingMode: number;
         wrapU: number;
         wrapV: number;
     }
-    interface IGLTFScene extends IGLTFChildRootProperty {
-        nodes: number[];
-        index: number;
+    interface ILoaderSampler extends ISampler, IArrayItem {
+        _data?: ILoaderSamplerData;
     }
-    interface IGLTFSkin extends IGLTFChildRootProperty {
-        inverseBindMatrices?: number;
-        skeleton?: number;
-        joints: number[];
-        index: number;
-        babylonSkeleton: Skeleton;
+    interface ILoaderScene extends IScene, IArrayItem {
     }
-    interface IGLTFTexture extends IGLTFChildRootProperty {
-        sampler?: number;
-        source: number;
-        index: number;
-        url?: string;
-        dataReadyObservable?: Observable<IGLTFTexture>;
-    }
-    interface IGLTFTextureInfo {
-        index: number;
-        texCoord?: number;
-    }
-    interface _IGLTF extends IGLTFProperty {
-        accessors?: IGLTFAccessor[];
-        animations?: IGLTFAnimation[];
-        asset: IGLTFAsset;
-        buffers?: IGLTFBuffer[];
-        bufferViews?: IGLTFBufferView[];
-        cameras?: IGLTFCamera[];
-        extensionsUsed?: string[];
-        extensionsRequired?: string[];
-        images?: IGLTFImage[];
-        materials?: IGLTFMaterial[];
-        meshes?: IGLTFMesh[];
-        nodes?: IGLTFNode[];
-        samplers?: IGLTFSampler[];
-        scene?: number;
-        scenes?: IGLTFScene[];
-        skins?: IGLTFSkin[];
-        textures?: IGLTFTexture[];
+    interface ILoaderSkin extends ISkin, IArrayItem {
+        _babylonSkeleton: Nullable<Skeleton>;
+        _loaded?: Promise<void>;
+    }
+    interface ILoaderTexture extends ITexture, IArrayItem {
+    }
+    interface ILoaderGLTF extends IGLTF {
+        accessors?: ILoaderAccessor[];
+        animations?: ILoaderAnimation[];
+        buffers?: ILoaderBuffer[];
+        bufferViews?: ILoaderBufferView[];
+        cameras?: ILoaderCamera[];
+        images?: ILoaderImage[];
+        materials?: ILoaderMaterial[];
+        meshes?: ILoaderMesh[];
+        nodes?: ILoaderNode[];
+        samplers?: ILoaderSampler[];
+        scenes?: ILoaderScene[];
+        skins?: ILoaderSkin[];
+        textures?: ILoaderTexture[];
     }
 }
 
 
 declare module BABYLON.GLTF2 {
     class GLTFLoader implements IGLTFLoader {
-        _gltf: _IGLTF;
+        _gltf: ILoaderGLTF;
         _babylonScene: Scene;
+        _completePromises: Promise<void>[];
         private _disposed;
+        private _state;
+        private _extensions;
         private _rootUrl;
-        private _defaultMaterial;
+        private _rootBabylonMesh;
         private _defaultSampler;
-        private _rootNode;
-        private _successCallback?;
         private _progressCallback?;
-        private _errorCallback?;
-        private _renderReady;
         private _requests;
-        private _renderReadyObservable;
-        private _renderPendingCount;
-        private _loaderPendingCount;
-        private _loaderTrackers;
-        static Extensions: {
-            [name: string]: GLTFLoaderExtension;
-        };
-        static RegisterExtension(extension: GLTFLoaderExtension): void;
+        private static _Names;
+        private static _Factories;
+        static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void;
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
         compileMaterials: boolean;
         useClipPlane: boolean;
         compileShadowGenerators: boolean;
-        onDisposeObservable: Observable<IGLTFLoader>;
-        onMeshLoadedObservable: Observable<AbstractMesh>;
-        onTextureLoadedObservable: Observable<BaseTexture>;
-        onMaterialLoadedObservable: Observable<Material>;
-        onCompleteObservable: Observable<IGLTFLoader>;
+        readonly onDisposeObservable: Observable<IGLTFLoader>;
+        readonly onMeshLoadedObservable: Observable<AbstractMesh>;
+        readonly onTextureLoadedObservable: Observable<BaseTexture>;
+        readonly onMaterialLoadedObservable: Observable<Material>;
+        readonly onCompleteObservable: Observable<IGLTFLoader>;
+        readonly state: Nullable<GLTFLoaderState>;
+        readonly extensions: IGLTFLoaderExtensions;
+        constructor();
         dispose(): void;
-        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void;
-        private _loadAsync(nodeNames, scene, data, rootUrl, onSuccess?, onProgress?, onError?);
-        private _onProgress();
-        _executeWhenRenderReady(func: () => void): void;
-        private _onRenderReady();
-        private _onComplete();
+        importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{
+            meshes: AbstractMesh[];
+            particleSystems: ParticleSystem[];
+            skeletons: Skeleton[];
+        }>;
+        loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+        private _loadAsync(nodes, scene, data, rootUrl, onProgress?);
         private _loadData(data);
+        private _setupData();
+        private _createRootNode();
+        private _loadNodesAsync(nodes);
+        _loadSceneAsync(context: string, scene: ILoaderScene): Promise<void>;
         private _getMeshes();
         private _getSkeletons();
         private _startAnimations();
-        private _loadDefaultScene(nodeNames);
-        private _loadScene(context, scene, nodeNames);
-        _loadNode(context: string, node: IGLTFNode): void;
-        private _loadMesh(context, node, mesh);
-        private _loadAllVertexDataAsync(context, mesh, onSuccess);
-        /**
-         * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4TextureCoordArray(context, data, accessor);
-        /**
-         * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
-         * @param {ArrayBufferView} data
-         * @param {IGLTFAccessor} accessor
-         */
-        private _convertToFloat4ColorArray(context, data, accessor);
-        private _loadVertexDataAsync(context, mesh, primitive, onSuccess);
-        private _createMorphTargets(context, node, mesh);
-        private _loadMorphTargets(context, node, mesh);
-        private _loadAllMorphTargetVertexDataAsync(context, node, mesh, onSuccess);
-        private _loadMorphTargetVertexDataAsync(context, vertexData, attributes, onSuccess);
-        private _loadTransform(node);
-        private _loadSkinAsync(context, skin, onSuccess);
+        _loadNodeAsync(context: string, node: ILoaderNode): Promise<void>;
+        private _loadMeshAsync(context, node, mesh);
+        private _loadPrimitiveAsync(context, node, mesh, primitive);
+        private _loadVertexDataAsync(context, primitive, babylonMesh);
+        private _createMorphTargets(context, node, mesh, primitive, babylonMesh);
+        private _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
+        private _loadMorphTargetVertexDataAsync(context, babylonVertexData, attributes, babylonMorphTarget);
+        private static _ConvertToFloat32Array(context, accessor, data);
+        private static _ConvertVec3ToVec4(context, data);
+        private static _LoadTransform(node, babylonNode);
+        private _loadSkinAsync(context, node, mesh, skin);
+        private _loadSkinInverseBindMatricesDataAsync(context, skin);
         private _createBone(node, skin, parent, localMatrix, baseMatrix, index);
-        private _loadBones(context, skin, inverseBindMatrixData);
-        private _loadBone(node, skin, inverseBindMatrixData, babylonBones);
+        private _loadBones(context, skin, inverseBindMatricesData);
+        private _loadBone(node, skin, inverseBindMatricesData, babylonBones);
         private _getNodeMatrix(node);
-        private _traverseNodes(context, indices, action, parentNode);
-        _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void;
-        private _loadAnimations();
-        private _loadAnimation(context, animation);
-        private _loadAnimationChannel(animation, channelContext, channel, samplerContext, sampler);
-        private _loadBufferAsync(context, buffer, onSuccess);
-        private _loadBufferViewAsync(context, bufferView, onSuccess);
-        private _loadAccessorAsync(context, accessor, onSuccess);
+        private _loadAnimationsAsync();
+        private _loadAnimationAsync(context, animation);
+        private _loadAnimationChannelAsync(context, animationContext, animation, channel, babylonAnimationGroup);
+        private _loadAnimationSamplerAsync(context, sampler);
+        private _loadBufferAsync(context, buffer);
+        private _loadBufferViewAsync(context, bufferView);
+        private _loadAccessorAsync(context, accessor);
         private _buildArrayBuffer<T>(typedArray, data, byteOffset, count, numComponents, byteStride?);
-        _addPendingData(data: any): void;
-        _removePendingData(data: any): void;
-        _addLoaderPendingData(data: any): void;
-        _removeLoaderPendingData(data: any): void;
-        _whenAction(action: () => void, onComplete: () => void): void;
         private _getDefaultMaterial();
-        private _loadMaterialMetallicRoughnessProperties(context, material);
-        _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void;
-        _createPbrMaterial(material: IGLTFMaterial): void;
-        _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void;
-        _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void;
-        _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex?: number): Texture;
+        private _loadMaterialMetallicRoughnessPropertiesAsync(context, material);
+        _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Promise<void>;
+        _createMaterial(material: ILoaderMaterial): PBRMaterial;
+        _loadMaterialBasePropertiesAsync(context: string, material: ILoaderMaterial): Promise<void>;
+        _loadMaterialAlphaProperties(context: string, material: ILoaderMaterial): void;
+        _loadTextureAsync(context: string, textureInfo: ITextureInfo, assign: (texture: Texture) => void): Promise<void>;
         private _loadSampler(context, sampler);
-        private _loadImageAsync(context, image, onSuccess);
-        _loadUriAsync(context: string, uri: string, onSuccess: (data: ArrayBufferView) => void): void;
-        _tryCatchOnError(handler: () => void): void;
-        private static _AssignIndices(array?);
-        static _GetProperty<T extends IGLTFProperty>(array?: ArrayLike<T>, index?: number): Nullable<T>;
-        private static _GetTextureWrapMode(context, mode?);
+        private _loadImageAsync(context, image);
+        _loadUriAsync(context: string, uri: string): Promise<ArrayBufferView>;
+        private _onProgress();
+        static _GetProperty<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T;
+        private static _GetTextureWrapMode(context, mode);
         private static _GetTextureSamplingMode(context, magFilter?, minFilter?);
         private static _GetNumComponents(context, type);
-        private _compileMaterialAsync(babylonMaterial, babylonMesh, onSuccess);
-        private _compileMaterialsAsync(onSuccess);
-        private _compileShadowGeneratorsAsync(onSuccess);
+        private static _ValidateUri(uri);
+        private _compileMaterialsAsync();
+        private _compileShadowGeneratorsAsync();
         private _abortRequests();
         private _releaseResources();
-    }
-}
-
-
-declare module BABYLON.GLTF2 {
-    /**
-    * Utils functions for GLTF
-    */
-    class GLTFUtils {
-        /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        static IsBase64(uri: string): boolean;
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        static DecodeBase64(uri: string): ArrayBuffer;
-        static ValidateUri(uri: string): boolean;
+        _applyExtensions<T>(actionAsync: (extension: GLTFLoaderExtension) => Nullable<Promise<T>>): Nullable<Promise<T>>;
     }
 }
 
@@ -1176,55 +1011,63 @@ declare module BABYLON.GLTF2 {
 declare module BABYLON.GLTF2 {
     abstract class GLTFLoaderExtension {
         enabled: boolean;
-        readonly abstract name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        protected _loadExtension<T>(context: string, property: IGLTFProperty, action: (context: string, extension: T, onComplete: () => void) => void): boolean;
-        static _Extensions: GLTFLoaderExtension[];
-        static TraverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        static LoadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
-        static LoadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        static LoadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        static LoadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private static _ApplyExtensions(action);
+        protected _loader: GLTFLoader;
+        constructor(loader: GLTFLoader);
+        protected readonly abstract _name: string;
+        /** Override this method to modify the default behavior for loading scenes. */
+        protected _loadSceneAsync(context: string, node: ILoaderScene): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading nodes. */
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading materials. */
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Override this method to modify the default behavior for loading uris. */
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
+        /** Helper method called by a loader extension to load an glTF extension. */
+        protected _loadExtensionAsync<T>(context: string, property: IProperty, actionAsync: (context: string, extension: T) => Promise<void>): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading scenes. */
+        static _LoadSceneAsync(loader: GLTFLoader, context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading nodes. */
+        static _LoadNodeAsync(loader: GLTFLoader, context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading materials. */
+        static _LoadMaterialAsync(loader: GLTFLoader, context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        /** Helper method called by the loader to allow extensions to override loading uris. */
+        static _LoadUriAsync(loader: GLTFLoader, context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class MSFTLOD extends GLTFLoaderExtension {
+        private _loadingNodeLOD;
+        private _loadNodeSignals;
+        private _loadingMaterialLOD;
+        private _loadMaterialSignals;
+        protected readonly _name: string;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>>;
         /**
-         * Specify the minimal delay between LODs in ms (default = 250)
+         * Gets an array of LOD properties from lowest to highest.
          */
-        Delay: number;
-        readonly name: string;
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        private _loadNodeLOD(loader, context, nodes, index, onComplete);
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadMaterialLOD(loader, context, materials, index, assign, onComplete);
+        private static _GetLODs<T>(context, property, array, ids);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRMaterialsPbrSpecularGlossiness extends GLTFLoaderExtension {
-        readonly name: string;
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean;
-        private _loadSpecularGlossinessProperties(loader, context, material, properties);
+        protected readonly _name: string;
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>>;
+        private _loadSpecularGlossinessPropertiesAsync(loader, context, material, properties);
     }
 }
 
 
 declare module BABYLON.GLTF2.Extensions {
     class KHRLights extends GLTFLoaderExtension {
-        readonly name: string;
-        private applyCommonProperties(light, lightInfo);
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean;
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean;
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean;
+        protected readonly _name: string;
+        protected _loadSceneAsync(context: string, scene: ILoaderScene): Nullable<Promise<void>>;
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>>;
+        private readonly _lights;
     }
 }

+ 1 - 1
dist/preview release/loaders/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-loaders",
     "description": "The Babylon.js file loaders library is an extension you can use to load different 3D file types into a Babylon scene.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 1 - 1
dist/preview release/materialsLibrary/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-materials",
     "description": "The Babylon.js materials library is a collection of advanced materials to be used in a Babylon.js scene.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 1 - 1
dist/preview release/postProcessesLibrary/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-post-process",
     "description": "The Babylon.js materials library is a collection of advanced materials to be used in a Babylon.js scene.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 1 - 1
dist/preview release/proceduralTexturesLibrary/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-procedural-textures",
     "description": "The Babylon.js materials library is a collection of advanced materials to be used in a Babylon.js scene.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 249 - 0
dist/preview release/serializers/babylonjs.serializers.module.d.ts

@@ -4,6 +4,255 @@
 declare module 'babylonjs-serializers' { 
     export = BABYLON; 
 }
+declare module BABYLON.GLTF2 {
+    const enum AccessorComponentType {
+        BYTE = 5120,
+        UNSIGNED_BYTE = 5121,
+        SHORT = 5122,
+        UNSIGNED_SHORT = 5123,
+        UNSIGNED_INT = 5125,
+        FLOAT = 5126,
+    }
+    const enum AccessorType {
+        SCALAR = "SCALAR",
+        VEC2 = "VEC2",
+        VEC3 = "VEC3",
+        VEC4 = "VEC4",
+        MAT2 = "MAT2",
+        MAT3 = "MAT3",
+        MAT4 = "MAT4",
+    }
+    const enum AnimationChannelTargetPath {
+        TRANSLATION = "translation",
+        ROTATION = "rotation",
+        SCALE = "scale",
+        WEIGHTS = "weights",
+    }
+    const enum AnimationSamplerInterpolation {
+        LINEAR = "LINEAR",
+        STEP = "STEP",
+        CUBICSPLINE = "CUBICSPLINE",
+    }
+    const enum CameraType {
+        PERSPECTIVE = "perspective",
+        ORTHOGRAPHIC = "orthographic",
+    }
+    const enum ImageMimeType {
+        JPEG = "image/jpeg",
+        PNG = "image/png",
+    }
+    const enum MaterialAlphaMode {
+        OPAQUE = "OPAQUE",
+        MASK = "MASK",
+        BLEND = "BLEND",
+    }
+    const enum MeshPrimitiveMode {
+        POINTS = 0,
+        LINES = 1,
+        LINE_LOOP = 2,
+        LINE_STRIP = 3,
+        TRIANGLES = 4,
+        TRIANGLE_STRIP = 5,
+        TRIANGLE_FAN = 6,
+    }
+    const enum TextureMagFilter {
+        NEAREST = 9728,
+        LINEAR = 9729,
+    }
+    const enum TextureMinFilter {
+        NEAREST = 9728,
+        LINEAR = 9729,
+        NEAREST_MIPMAP_NEAREST = 9984,
+        LINEAR_MIPMAP_NEAREST = 9985,
+        NEAREST_MIPMAP_LINEAR = 9986,
+        LINEAR_MIPMAP_LINEAR = 9987,
+    }
+    const enum TextureWrapMode {
+        CLAMP_TO_EDGE = 33071,
+        MIRRORED_REPEAT = 33648,
+        REPEAT = 10497,
+    }
+    interface IProperty {
+        extensions?: {
+            [key: string]: any;
+        };
+        extras?: any;
+    }
+    interface IChildRootProperty extends IProperty {
+        name?: string;
+    }
+    interface IAccessorSparseIndices extends IProperty {
+        bufferView: number;
+        byteOffset?: number;
+        componentType: AccessorComponentType;
+    }
+    interface IAccessorSparseValues extends IProperty {
+        bufferView: number;
+        byteOffset?: number;
+    }
+    interface IAccessorSparse extends IProperty {
+        count: number;
+        indices: IAccessorSparseIndices;
+        values: IAccessorSparseValues;
+    }
+    interface IAccessor extends IChildRootProperty {
+        bufferView?: number;
+        byteOffset?: number;
+        componentType: AccessorComponentType;
+        normalized?: boolean;
+        count: number;
+        type: AccessorType;
+        max?: number[];
+        min?: number[];
+        sparse?: IAccessorSparse;
+    }
+    interface IAnimationChannel extends IProperty {
+        sampler: number;
+        target: IAnimationChannelTarget;
+    }
+    interface IAnimationChannelTarget extends IProperty {
+        node: number;
+        path: AnimationChannelTargetPath;
+    }
+    interface IAnimationSampler extends IProperty {
+        input: number;
+        interpolation?: AnimationSamplerInterpolation;
+        output: number;
+    }
+    interface IAnimation extends IChildRootProperty {
+        channels: IAnimationChannel[];
+        samplers: IAnimationSampler[];
+    }
+    interface IAsset extends IChildRootProperty {
+        copyright?: string;
+        generator?: string;
+        version: string;
+        minVersion?: string;
+    }
+    interface IBuffer extends IChildRootProperty {
+        uri?: string;
+        byteLength: number;
+    }
+    interface IBufferView extends IChildRootProperty {
+        buffer: number;
+        byteOffset?: number;
+        byteLength: number;
+        byteStride?: number;
+    }
+    interface ICameraOrthographic extends IProperty {
+        xmag: number;
+        ymag: number;
+        zfar: number;
+        znear: number;
+    }
+    interface ICameraPerspective extends IProperty {
+        aspectRatio: number;
+        yfov: number;
+        zfar: number;
+        znear: number;
+    }
+    interface ICamera extends IChildRootProperty {
+        orthographic?: ICameraOrthographic;
+        perspective?: ICameraPerspective;
+        type: CameraType;
+    }
+    interface IImage extends IChildRootProperty {
+        uri?: string;
+        mimeType?: ImageMimeType;
+        bufferView?: number;
+    }
+    interface IMaterialNormalTextureInfo extends ITextureInfo {
+        scale?: number;
+    }
+    interface IMaterialOcclusionTextureInfo extends ITextureInfo {
+        strength?: number;
+    }
+    interface IMaterialPbrMetallicRoughness {
+        baseColorFactor?: number[];
+        baseColorTexture?: ITextureInfo;
+        metallicFactor?: number;
+        roughnessFactor?: number;
+        metallicRoughnessTexture?: ITextureInfo;
+    }
+    interface IMaterial extends IChildRootProperty {
+        pbrMetallicRoughness?: IMaterialPbrMetallicRoughness;
+        normalTexture?: IMaterialNormalTextureInfo;
+        occlusionTexture?: IMaterialOcclusionTextureInfo;
+        emissiveTexture?: ITextureInfo;
+        emissiveFactor?: number[];
+        alphaMode?: MaterialAlphaMode;
+        alphaCutoff?: number;
+        doubleSided?: boolean;
+    }
+    interface IMeshPrimitive extends IProperty {
+        attributes: {
+            [name: string]: number;
+        };
+        indices?: number;
+        material?: number;
+        mode?: MeshPrimitiveMode;
+        targets?: {
+            [name: string]: number;
+        }[];
+    }
+    interface IMesh extends IChildRootProperty {
+        primitives: IMeshPrimitive[];
+        weights?: number[];
+    }
+    interface INode extends IChildRootProperty {
+        camera?: number;
+        children?: number[];
+        skin?: number;
+        matrix?: number[];
+        mesh?: number;
+        rotation?: number[];
+        scale?: number[];
+        translation?: number[];
+        weights?: number[];
+    }
+    interface ISampler extends IChildRootProperty {
+        magFilter?: TextureMagFilter;
+        minFilter?: TextureMinFilter;
+        wrapS?: TextureWrapMode;
+        wrapT?: TextureWrapMode;
+    }
+    interface IScene extends IChildRootProperty {
+        nodes: number[];
+    }
+    interface ISkin extends IChildRootProperty {
+        inverseBindMatrices?: number;
+        skeleton?: number;
+        joints: number[];
+    }
+    interface ITexture extends IChildRootProperty {
+        sampler?: number;
+        source: number;
+    }
+    interface ITextureInfo {
+        index: number;
+        texCoord?: number;
+    }
+    interface IGLTF extends IProperty {
+        accessors?: IAccessor[];
+        animations?: IAnimation[];
+        asset: IAsset;
+        buffers?: IBuffer[];
+        bufferViews?: IBufferView[];
+        cameras?: ICamera[];
+        extensionsUsed?: string[];
+        extensionsRequired?: string[];
+        images?: IImage[];
+        materials?: IMaterial[];
+        meshes?: IMesh[];
+        nodes?: INode[];
+        samplers?: ISampler[];
+        scene?: number;
+        scenes?: IScene[];
+        skins?: ISkin[];
+        textures?: ITexture[];
+    }
+}
+
 
 declare module BABYLON {
     class OBJExport {

+ 1 - 1
dist/preview release/serializers/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-serializers",
     "description": "The Babylon.js serializers library is an extension you can use to serialize Babylon scenes.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

File diff suppressed because it is too large
+ 4873 - 7839
dist/preview release/typedocValidationBaseline.json


File diff suppressed because it is too large
+ 64 - 64
dist/preview release/viewer/babylon.viewer.js


+ 1 - 1
dist/preview release/viewer/package.json

@@ -4,7 +4,7 @@
     },
     "name": "babylonjs-viewer",
     "description": "A simple-to-use viewer based on BabylonJS to display 3D elements natively",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 21 - 2
dist/preview release/what's new.md

@@ -1,6 +1,7 @@
 # 3.2.0
 
 ## Major updates
+
 - Improved building process: We now run a full visual validation test for each pull request. Furthermore, code comments and what's new updates are now mandatory ([sebavan](https://github.com/sebavan))
 - Introduced texture binding atlas. This optimization allows the engine to reuse texture bindings instead of rebinding textures when they are not on constant sampler indexes ([deltakosh](https://github.com/deltakosh))
 - New [AnimationGroup class](http://doc.babylonjs.com/how_to/group) to control simultaneously multiple animations with different targets ([deltakosh](https://github.com/deltakosh))
@@ -8,8 +9,11 @@
 - New glTF [serializer](https://github.com/BabylonJS/Babylon.js/tree/master/serializers/src/glTF/2.0). You can now export glTF or glb files directly from a Babylon scene ([kcoley](https://github.com/kcoley))
 - Babylon.js now uses Promises in addition to callbacks. We created several `xxxAsync` functions all over the framework (`SceneLoader.AppendAsync` for instance, which returns a Promise). A polyfill is also integrated to support older browsers ([deltakosh](https://github.com/deltakosh))
 - Introduced [Projection Texture on SpotLight](http://doc.babylonjs.com/babylon101/lights#projection-texture) ([lostink](https://github.com/lostink))
+- Introduced support for [local cubemaps](http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode) ([deltakosh](https://github.com/deltakosh))
+- Added VideoDome class to provide a template for a common scenario, and gave it FOV control ([DavidHGillen](https://github.com/DavidHGillen))
 
 ## Updates
+
 - Tons of functions and classes received the code comments they deserved (All the community)
 - Added support for all RGBA orders (BGR, RGB, etc..) for the DDS loader ([deltakosh](https://github.com/deltakosh))
 - Improved [SceneOptimizer](http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer) to provide better adaptability ([deltakosh](https://github.com/deltakosh))
@@ -45,13 +49,28 @@
 - SPS internal storage of each solid particle rotation matrix ([jbousquie](https://github.com/jbousquie)) 
 - (Viewer) Introducing the viewer labs - testing new features. ([RaananW](https://github.com/RaananW))
 - AssetContainer Class and loading methods. ([trevordev](https://github.com/trevordev))
-- KeepAssets class and AssetContainer.moveAllFromScene ([HoloLite](http://www.html5gamedevs.com/profile/28694-hololite/), [trevordev](https://github.com/trevordev))
+- KeepAssets class and AssetContainer.moveAllFromScene ([HoloLite](http://www.html5gamedevs.com/profile/28694-hololite/) [trevordev](https://github.com/trevordev))
 - (Viewer) It is now possible to update parts of the configuration without rcreating the objects. ([RaananW](https://github.com/RaananW))
+- (Gulp) extra/external declarations can be prepended to final declarations during build. ([RaananW](https://github.com/RaananW))
+- (Viewer) Model can be normalized using configuration. ([RaananW](https://github.com/RaananW))
+- (Gulp) extra/external declarations can be prepended to final NPM declarations during build. ([RaananW](https://github.com/RaananW))
+- GUI.Line can have its world position set from one end or the other ([SvenFrankson](https://github.com/SvenFrankson))
+- Added FOV system to background material for zoom effects in skyboxes without adjusting camera FOV ([DavidHGillen](https://github.com/DavidHGillen))
+- Improved glTF loader by using promises for asynchronous operations. ([bghgary](https://github.com/bghgary)]
+- Improved glTF loader performance by compiling materials in parallel with downloading external resources. ([bghgary](https://github.com/bghgary)]
+- Added unit tests for the glTF 2.0 loader. ([bghgary](https://github.com/bghgary)]
+- Added promise-based async functions to the SceneLoader, Scene.whenReadyAsync, and material.forceCompilationAsync. ([bghgary](https://github.com/bghgary)]
+- Added checks to VertexData.merge to ensure data is valid before merging. ([bghgary](https://github.com/bghgary)]
 
 ## Bug fixes
+
 - `setPivotMatrix` ws not setting pivot correctly. This is now fixed. We also introduced a new `setPreTransformMatrix` to reproduce the sometimes needed behavior of the previous `setPivotMatrix` function ([deltakosh](https://github.com/deltakosh))
+- SPS solid particle `.pivot` property now also behaves like the standard mesh pivot. Former behavior (particle translation) can be kept with the particle property `.translateFromPivot` set to true ([jbousquie](https://github.com/jbousquie))
 - Texture extension detection in `Engine.CreateTexture` ([sebavan](https://github.com/sebavan))
-- Fixed a bug with merging vertex data ([bghgary](https://github.com/bghgary))
+- SPS internal temporary vector3 instead of Tmp.Vector3 to avoid possible concurrent uses ([jbousquie](https://github.com/jbousquie))
 
 ## Breaking changes
+
 - Removed unused PostProcessRenderPass class and extended postProcessingRenderingEffect to support multiple PostProcesses ([trevordev](https://github.com/trevordev))
+- VertexData.merge no longer supports merging of data that do not have the same set of attributes. ([bghgary](https://github.com/bghgary)]
+- glTF 2.0 loader will now create a mesh for each primitive instead of merging the primitives together into one mesh. ([bghgary](https://github.com/bghgary)]

+ 45 - 7
gui/src/controls/line.ts

@@ -179,14 +179,52 @@ module BABYLON.GUI {
         protected _computeAlignment(parentMeasure: Measure, context: CanvasRenderingContext2D): void {          
             this._currentMeasure.left = Math.min(this._x1.getValue(this._host), this._effectiveX2) - this._lineWidth / 2;
             this._currentMeasure.top = Math.min(this._y1.getValue(this._host), this._effectiveY2) - this._lineWidth / 2;            
-        }   
+        }
+
+        /**
+         * Move one end of the line given 3D cartesian coordinates.
+         * @param position Targeted world position
+         * @param scene Scene
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        public moveToVector3(position: Vector3, scene: Scene, end: boolean = false): void {
+            if (!this._host || this._root !== this._host._rootContainer) {
+                Tools.Error("Cannot move a control to a vector3 if the control is not at root level");
+                return;
+            }
+
+            var globalViewport = this._host._getGlobalViewport(scene);
+            var projectedPosition = Vector3.Project(position, Matrix.Identity(), scene.getTransformMatrix(), globalViewport);
 
-        public _moveToProjectedPosition(projectedPosition: Vector3): void {
-            this.x1 = (projectedPosition.x + this._linkOffsetX.getValue(this._host)) + "px";
-            this.y1 = (projectedPosition.y + this._linkOffsetY.getValue(this._host)) + "px";
+            this._moveToProjectedPosition(projectedPosition, end)
 
-            this._x1.ignoreAdaptiveScaling = true;
-            this._y1.ignoreAdaptiveScaling = true;
+            if (projectedPosition.z < 0 || projectedPosition.z > 1) {
+                this.notRenderable = true;
+                return;
+            }
+            this.notRenderable = false;
+        }
+
+        /**
+         * Move one end of the line to a position in screen absolute space.
+         * @param projectedPosition Position in screen absolute space (X, Y)
+         * @param end (opt) Set to true to assign x2 and y2 coordinates of the line. Default assign to x1 and y1.
+         */
+        public _moveToProjectedPosition(projectedPosition: Vector3, end: boolean = false): void {
+            let x: string = (projectedPosition.x + this._linkOffsetX.getValue(this._host)) + "px";
+            let y: string = (projectedPosition.y + this._linkOffsetY.getValue(this._host)) + "px";
+
+            if (end) {
+                this.x2 = x;
+                this.y2 = y;
+                this._x2.ignoreAdaptiveScaling = true;
+                this._y2.ignoreAdaptiveScaling = true;
+            } else {
+                this.x1 = x;
+                this.y1 = y;
+                this._x1.ignoreAdaptiveScaling = true;
+                this._y1.ignoreAdaptiveScaling = true;
+            }
         }
     }    
-}
+}

+ 4 - 7
loaders/src/OBJ/babylon.objFileLoader.ts

@@ -264,14 +264,11 @@ module BABYLON {
             return this.importMesh(null, scene, data, rootUrl, null, null, null);
         }
 
-        public loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void):Nullable<AssetContainer>{
+        public loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer {
             var container = new AssetContainer(scene);
-            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
-            if(result){
-                container.removeAllFromScene();
-                return container;
-            }
-            return null;
+            this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            container.removeAllFromScene();
+            return container;
         }
 
         /**

+ 4 - 7
loaders/src/STL/babylon.stlFileLoader.ts

@@ -86,14 +86,11 @@ module BABYLON {
             return result;
         }
 
-        public loadAssets(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void):Nullable<AssetContainer>{
+        public loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer {
             var container = new AssetContainer(scene);
-            var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
-            if(result){
-                container.removeAllFromScene();
-                return container;
-            }
-            return null;
+            this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
+            container.removeAllFromScene();
+            return container;
         }
 
         private isBinary (data: any) {

+ 42 - 12
loaders/src/glTF/1.0/babylon.glTFLoader.ts

@@ -584,9 +584,7 @@ module BABYLON.GLTF1 {
 
         const subMaterials: Material[] = [];
 
-        var vertexData = new VertexData();
-        var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
-
+        var vertexData: Nullable<VertexData> = null;
         var verticesStarts = new Array<number>();
         var verticesCounts = new Array<number>();
         var indexStarts = new Array<number>();
@@ -684,7 +682,12 @@ module BABYLON.GLTF1 {
                     indexCounts.push(tempVertexData.indices.length);
                 }
 
-                vertexData.merge(tempVertexData);
+                if (!vertexData) {
+                    vertexData = tempVertexData;
+                }
+                else {
+                    vertexData.merge(tempVertexData);
+                }
 
                 // Sub material
                 let material = gltfRuntime.scene.getMaterialByID(primitive.material);
@@ -714,7 +717,7 @@ module BABYLON.GLTF1 {
         }
 
         // Apply geometry
-        geometry.setAllVerticesData(vertexData, false);
+        new Geometry(id, gltfRuntime.scene, vertexData!, false, newMesh);
         newMesh.computeWorldMatrix(true);
 
         // Apply submeshes
@@ -1292,8 +1295,8 @@ module BABYLON.GLTF1 {
         public static LoadBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: (message: string) => void, onProgress?: () => void): void {
             var buffer: IGLTFBuffer = gltfRuntime.buffers[id];
 
-            if (GLTFUtils.IsBase64(buffer.uri)) {
-                setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(buffer.uri))));
+            if (Tools.IsBase64(buffer.uri)) {
+                setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))));
             }
             else {
                 Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, data => onSuccess(new Uint8Array(data as ArrayBuffer)), onProgress, undefined, true, request => {
@@ -1319,8 +1322,8 @@ module BABYLON.GLTF1 {
 
             var source: IGLTFImage = gltfRuntime.images[texture.source];
 
-            if (GLTFUtils.IsBase64(source.uri)) {
-                setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(source.uri))));
+            if (Tools.IsBase64(source.uri)) {
+                setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))));
             }
             else {
                 Tools.LoadFile(gltfRuntime.rootUrl + source.uri, data => onSuccess(new Uint8Array(data as ArrayBuffer)), undefined, undefined, true, request => {
@@ -1368,7 +1371,7 @@ module BABYLON.GLTF1 {
         public static LoadShaderStringAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (shaderString: string) => void, onError: (message: string) => void): void {
             var shader: IGLTFShader = gltfRuntime.shaders[id];
 
-            if (GLTFUtils.IsBase64(shader.uri)) {
+            if (Tools.IsBase64(shader.uri)) {
                 var shaderString = atob(shader.uri.split(",")[1]);
                 onSuccess(shaderString);
             }
@@ -1570,10 +1573,13 @@ module BABYLON.GLTF1 {
         public onMaterialLoadedObservable = new Observable<Material>();
         public onCompleteObservable = new Observable<IGLTFLoader>();
 
+        public state: Nullable<GLTFLoaderState> = null;
+        public extensions: Nullable<IGLTFLoaderExtensions> = null;
+
         public dispose(): void {}
         // #endregion
 
-        public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): boolean {
+        private _importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): boolean {
             scene.useRightHandedSystem = true;
 
             GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
@@ -1636,7 +1642,21 @@ module BABYLON.GLTF1 {
             return true;
         }
 
-        public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): void {
+        public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }> {
+            return new Promise((resolve, reject) => {
+                this._importMeshAsync(meshesNames, scene, data, rootUrl, (meshes, particleSystems, skeletons) => {
+                    resolve({
+                        meshes: meshes,
+                        particleSystems: particleSystems,
+                        skeletons: skeletons
+                    });
+                }, onProgress, message => {
+                    reject(new Error(message));
+                });
+            });
+        }
+
+        private _loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: SceneLoaderProgressEvent) => void, onError: (message: string) => void): void {
             scene.useRightHandedSystem = true;
 
             GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
@@ -1664,6 +1684,16 @@ module BABYLON.GLTF1 {
             }, onError);
         }
 
+        public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress: (event: SceneLoaderProgressEvent) => void): Promise<void> {
+            return new Promise((resolve, reject) => {
+                this._loadAsync(scene, data, rootUrl, () => {
+                    resolve();
+                }, onProgress, message => {
+                    reject(new Error(message));
+                });
+            });
+        }
+
         private _loadShadersAsync(gltfRuntime: IGLTFRuntime, onload: () => void): void {
             var hasShaders = false;
 

+ 0 - 24
loaders/src/glTF/1.0/babylon.glTFLoaderUtils.ts

@@ -84,30 +84,6 @@ module BABYLON.GLTF1 {
         }
 
         /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        public static IsBase64(uri: string): boolean {
-            return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
-        }
-
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        public static DecodeBase64(uri: string): ArrayBuffer {
-            var decodedString = atob(uri.split(",")[1]);
-            var bufferLength = decodedString.length;
-            var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
-
-            for (var i = 0; i < bufferLength; i++) {
-                bufferView[i] = decodedString.charCodeAt(i);
-            }
-
-            return bufferView.buffer;
-        }
-
-        /**
         * Returns the wrap mode of the texture
         * @param mode: the mode value
         */

+ 78 - 90
loaders/src/glTF/2.0/Extensions/KHR_lights.ts

@@ -1,119 +1,107 @@
 /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
 
 module BABYLON.GLTF2.Extensions {
-    interface IGLTFLight {
-        type: "directional" | "point" | "spot";
-        color: [number, number, number];
-        intensity: number;
-        // Runtime values
-        index: number;
-    }
+    // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
+
+    const NAME = "KHR_lights";
 
-    interface IKHRLights {
-        lights: IGLTFLight[];
+    enum LightType {
+        AMBIENT = "ambient",
+        DIRECTIONAL = "directional",
+        POINT = "point",
+        SPOT = "spot"
     }
 
-    interface IGLTFLightReference {
+    interface ILightReference {
         light: number;
-        // Runtime values
-        babylonLight: Light;
     }
 
-    export class KHRLights extends GLTFLoaderExtension {
-        public get name(): string {
-            return "KHR_lights";
-        }
+    interface ILight {
+        type: LightType;
+        color?: number[];
+        intensity?: number;
+    }
 
-        private applyCommonProperties(light: Light, lightInfo: IGLTFLight): void {
-            if (lightInfo.color) {
-                light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
-            } else {
-                light.diffuse.copyFromFloats(1, 1, 1);
-            }
+    interface ISpotLight extends ILight {
+        innerConeAngle?: number;
+        outerConeAngle?: number;
+    }
 
-            if (lightInfo.intensity !== undefined) {
-                light.intensity = lightInfo.intensity;
-            } else {
-                light.intensity = 1;
-            }
+    interface ILights {
+        lights: ILight[];
+    }
+
+    export class KHRLights extends GLTFLoaderExtension {
+        protected get _name(): string {
+            return NAME;
         }
 
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean { 
-            return this._loadExtension<IGLTFLightReference>(context, scene, (context, extension, onComplete) => {
-                if (extension.light >= 0 && loader._gltf.extensions) {
-                    const lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
-                    if (lightInfo.type !== 'ambient') {
-                        return;
-                    }
+        protected _loadSceneAsync(context: string, scene: ILoaderScene): Nullable<Promise<void>> { 
+            return this._loadExtensionAsync<ILightReference>(context, scene, (context, extension) => {
+                const promise = this._loader._loadSceneAsync(context, scene);
 
-                    const lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
-                    loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
+                const light = GLTFLoader._GetProperty(context, this._lights, extension.light);
+                if (light.type !== LightType.AMBIENT) {
+                    throw new Error(context + ": Only ambient lights are allowed on a scene");
                 }
-                
-                onComplete();
+
+                this._loader._babylonScene.ambientColor = light.color ? Color3.FromArray(light.color) : Color3.Black();
+
+                return promise;
             });
         }
 
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean { 
-            return this._loadExtension<IGLTFLightReference>(context, node, (context, extension, onComplete) => {
-                if (extension.light >= 0 && loader._gltf.extensions) {
-                    const lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
-                    const name = node.name || 'Light';
-                    let matrix: Matrix;
-                    if (node.matrix) {
-                        matrix = Matrix.FromArray(node.matrix);
-                    } else {
-                        matrix = Matrix.Identity();
-                    }
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>> { 
+            return this._loadExtensionAsync<ILightReference>(context, node, (context, extension) => {
+                const promise = this._loader._loadNodeAsync(context, node);
 
-                    const direction = new Vector3(0, 0, 1);
-                    if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
-                        const rotationMatrix = matrix.getRotationMatrix();
-                        Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
-                    }
+                let babylonLight: Light;
 
-                    let light: Light;
-                    if (lightInfo.type == 'directional') {
-                        light = new DirectionalLight(name, direction, loader._babylonScene);
-                    } else {
-                        const position = matrix.getTranslation();
-                        if (lightInfo.type == 'spot') {
-                            const angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
-                            light = new SpotLight(name, position, direction, angle, 2, loader._babylonScene);
-                        } else {
-                            light = new PointLight(name, position, loader._babylonScene);
-                        }
-                    } 
-
-                    this.applyCommonProperties(light, lightInfo);
-                    
-                    extension.babylonLight = light;
-                    extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
-                    
-                    if (node.children) {
-                        for (const index of node.children) {
-                            const childNode = GLTFLoader._GetProperty(loader._gltf.nodes, index);
-                            if (!childNode) {
-                                throw new Error(context + ": Failed to find child node " + index);
-                            }
-        
-                            loader._loadNode("#/nodes/" + index, childNode);
-                        }
+                const light = GLTFLoader._GetProperty(context, this._lights, extension.light);
+                const name = node._babylonMesh!.name;
+                switch (light.type) {
+                    case LightType.AMBIENT: {
+                        throw new Error(context + ": Ambient lights are not allowed on a node");
+                    }
+                    case LightType.DIRECTIONAL: {
+                        babylonLight = new DirectionalLight(name, Vector3.Forward(), this._loader._babylonScene);
+                        break;
+                    }
+                    case LightType.POINT: {
+                        babylonLight = new PointLight(name, Vector3.Zero(), this._loader._babylonScene);
+                        break;
+                    }
+                    case LightType.SPOT: {
+                        const spotLight = light as ISpotLight;
+                        // TODO: support inner and outer cone angles
+                        //const innerConeAngle = spotLight.innerConeAngle || 0;
+                        const outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
+                        babylonLight = new SpotLight(name, Vector3.Zero(), Vector3.Forward(), outerConeAngle, 2, this._loader._babylonScene);
+                        break;
+                    }
+                    default: {
+                        throw new Error(context + ": Invalid light type " + light.type);
                     }
                 }
-                onComplete();
+
+                babylonLight.diffuse = light.color ? Color3.FromArray(light.color) : Color3.White();
+                babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
+                babylonLight.parent = node._babylonMesh!;
+
+                return promise;
             });
         }
 
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean {
-            return this._loadExtension<IKHRLights>(context, root, (context, extension, onComplete) => {
-                extension.lights.forEach((light: IGLTFLight, idx: number) => {
-                    light.index = idx;
-                });
-                onComplete();
-            });
+        private get _lights(): Array<ILight> {
+            const extensions = this._loader._gltf.extensions;
+            if (!extensions || !extensions[this._name]) {
+                throw new Error("#/extensions: " + this._name + " not found");
+            }
+
+            const extension = extensions[this._name] as ILights;
+            return extension.lights;
         }
     }
 
-    GLTFLoader.RegisterExtension(new KHRLights());
+    GLTFLoader._Register(NAME, loader => new KHRLights(loader));
 }

+ 55 - 29
loaders/src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts

@@ -1,59 +1,85 @@
 /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
 
 module BABYLON.GLTF2.Extensions {
+    // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
+
+    const NAME = "KHR_materials_pbrSpecularGlossiness";
+
     interface IKHRMaterialsPbrSpecularGlossiness {
         diffuseFactor: number[];
-        diffuseTexture: IGLTFTextureInfo;
+        diffuseTexture: ITextureInfo;
         specularFactor: number[];
         glossinessFactor: number;
-        specularGlossinessTexture: IGLTFTextureInfo;
+        specularGlossinessTexture: ITextureInfo;
     }
 
     export class KHRMaterialsPbrSpecularGlossiness extends GLTFLoaderExtension {
-        public get name(): string {
-            return "KHR_materials_pbrSpecularGlossiness";
+        protected get _name(): string {
+            return NAME;
         }
 
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean {
-            return this._loadExtension<IKHRMaterialsPbrSpecularGlossiness>(context, material, (context, extension, onComplete) => {
-                loader._createPbrMaterial(material);
-                loader._loadMaterialBaseProperties(context, material);
-                this._loadSpecularGlossinessProperties(loader, context, material, extension);
-                assign(material.babylonMaterial, true);
-                onComplete();
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>> {
+            return this._loadExtensionAsync<IKHRMaterialsPbrSpecularGlossiness>(context, material, (context, extension) => {
+                material._babylonMeshes = material._babylonMeshes || [];
+                material._babylonMeshes.push(babylonMesh);
+
+                if (material._loaded) {
+                    babylonMesh.material = material._babylonMaterial!;
+                    return material._loaded;
+                }
+
+                const promises = new Array<Promise<void>>();
+
+                const babylonMaterial = this._loader._createMaterial(material);
+                material._babylonMaterial = babylonMaterial;
+
+                promises.push(this._loader._loadMaterialBasePropertiesAsync(context, material));
+                promises.push(this._loadSpecularGlossinessPropertiesAsync(this._loader, context, material, extension));
+
+                this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
+
+                babylonMesh.material = babylonMaterial;
+
+                return (material._loaded = Promise.all(promises).then(() => {}));
             });
         }
 
-        private _loadSpecularGlossinessProperties(loader: GLTFLoader, context: string, material: IGLTFMaterial, properties: IKHRMaterialsPbrSpecularGlossiness): void {
-            const babylonMaterial = material.babylonMaterial as PBRMaterial;
+        private _loadSpecularGlossinessPropertiesAsync(loader: GLTFLoader, context: string, material: ILoaderMaterial, properties: IKHRMaterialsPbrSpecularGlossiness): Promise<void> {
+            const promises = new Array<Promise<void>>();
 
-            babylonMaterial.albedoColor = properties.diffuseFactor ? Color3.FromArray(properties.diffuseFactor) : new Color3(1, 1, 1);
-            babylonMaterial.reflectivityColor = properties.specularFactor ? Color3.FromArray(properties.specularFactor) : new Color3(1, 1, 1);
-            babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
+            const babylonMaterial = material._babylonMaterial as PBRMaterial;
 
-            if (properties.diffuseTexture) {
-                const texture = GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
-                if (!texture) {
-                    throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
-                }
+            if (properties.diffuseFactor) {
+                babylonMaterial.albedoColor = Color3.FromArray(properties.diffuseFactor);
+                babylonMaterial.alpha = properties.diffuseFactor[3];
+            }
+            else {
+                babylonMaterial.albedoColor = Color3.White();
+            }
 
-                babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
+            babylonMaterial.reflectivityColor = properties.specularFactor ? Color3.FromArray(properties.specularFactor) : Color3.White();
+            babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
+
+            if (properties.diffuseTexture) {
+                promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, texture => {
+                    babylonMaterial.albedoTexture = texture;
+                }));
             }
 
             if (properties.specularGlossinessTexture) {
-                const texture = GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
-                if (!texture) {
-                    throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
-                }
+                promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, texture => {
+                    babylonMaterial.reflectivityTexture = texture;
+                }));
 
-                babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
                 babylonMaterial.reflectivityTexture.hasAlpha = true;
                 babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
             }
 
-            loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
+            loader._loadMaterialAlphaProperties(context, material);
+
+            return Promise.all(promises).then(() => {});
         }
     }
 
-    GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
+    GLTFLoader._Register(NAME, loader => new KHRMaterialsPbrSpecularGlossiness(loader));
 }

+ 92 - 92
loaders/src/glTF/2.0/Extensions/MSFT_lod.ts

@@ -1,128 +1,128 @@
 /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
 
 module BABYLON.GLTF2.Extensions {
+    // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
+
+    const NAME = "MSFT_lod";
+
     interface IMSFTLOD {
         ids: number[];
     }
 
-    // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
     export class MSFTLOD extends GLTFLoaderExtension {
-        /**
-         * Specify the minimal delay between LODs in ms (default = 250)
-         */
-        public Delay = 250;
+        private _loadingNodeLOD: Nullable<ILoaderNode> = null;
+        private _loadNodeSignals: { [nodeIndex: number]: Deferred<void> } = {};
+
+        private _loadingMaterialLOD: Nullable<ILoaderMaterial> = null;
+        private _loadMaterialSignals: { [materialIndex: number]: Deferred<void> } = {};
 
-        public get name() {
-            return "MSFT_lod";
+        protected get _name() {
+            return NAME;
         }
 
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean {
-            return this._loadExtension<IMSFTLOD>(context, node, (context, extension, onComplete) => {
-                for (let i = extension.ids.length - 1; i >= 0; i--) {
-                    const lodNode = GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
-                    if (!lodNode) {
-                        throw new Error(context + ": Failed to find node " + extension.ids[i]);
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>> {
+            return this._loadExtensionAsync<IMSFTLOD>(context, node, (context, extension) => {
+                let firstPromise: Promise<void>;
+
+                const nodeLODs = MSFTLOD._GetLODs(context, node, this._loader._gltf.nodes, extension.ids);
+                for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
+                    const nodeLOD = nodeLODs[indexLOD];
+
+                    if (indexLOD !== 0) {
+                        this._loadingNodeLOD = nodeLOD;
+                        this._loadNodeSignals[nodeLOD._index] = new Deferred<void>();
                     }
 
-                    loader._traverseNode(context, lodNode, action, parentNode);
-                }
+                    const promise = this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(() => {
+                        if (indexLOD !== 0) {
+                            const previousNodeLOD = nodeLODs[indexLOD - 1];
+                            previousNodeLOD._babylonMesh!.setEnabled(false);
+                        }
 
-                loader._traverseNode(context, node, action, parentNode);
-                onComplete();
-            });
-        }
+                        if (indexLOD !== nodeLODs.length - 1) {
+                            const nodeIndex = nodeLODs[indexLOD + 1]._index;
+                            this._loadNodeSignals[nodeIndex].resolve();
+                            delete this._loadNodeSignals[nodeIndex];
+                        }
+                    });
 
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean {
-            return this._loadExtension<IMSFTLOD>(context, node, (context, extension, onComplete) => {
-                const nodes = [node];
-                for (let index of extension.ids) {
-                    const lodNode = GLTFLoader._GetProperty(loader._gltf.nodes, index);
-                    if (!lodNode) {
-                        throw new Error(context + ": Failed to find node " + index);
+                    if (indexLOD === 0) {
+                        firstPromise = promise;
+                    }
+                    else {
+                        this._loader._completePromises.push(promise);
+                        this._loadingNodeLOD = null;
                     }
-
-                    nodes.push(lodNode);
                 }
 
-                loader._addLoaderPendingData(node);
-                this._loadNodeLOD(loader, context, nodes, nodes.length - 1, () => {
-                    loader._removeLoaderPendingData(node);
-                    onComplete();
-                });
+                return firstPromise!;
             });
         }
 
-        private _loadNodeLOD(loader: GLTFLoader, context: string, nodes: IGLTFNode[], index: number, onComplete: () => void): void {
-            loader._whenAction(() => {
-                loader._loadNode(context, nodes[index]);
-            }, () => {
-                if (index !== nodes.length - 1) {
-                    const previousNode = nodes[index + 1];
-                    previousNode.babylonMesh.setEnabled(false);
-                }
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>> {
+            return this._loadExtensionAsync<IMSFTLOD>(context, material, (context, extension) => {
+                let firstPromise: Promise<void>;
 
-                if (index === 0) {
-                    onComplete();
-                    return;
-                }
+                const materialLODs = MSFTLOD._GetLODs(context, material, this._loader._gltf.materials, extension.ids);
+                for (let indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
+                    const materialLOD = materialLODs[indexLOD];
+
+                    if (indexLOD !== 0) {
+                        this._loadingMaterialLOD = materialLOD;
+                        this._loadMaterialSignals[materialLOD._index] = new Deferred<void>();
+                    }
 
-                setTimeout(() => {
-                    loader._tryCatchOnError(() => {
-                        this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
+                    const promise = this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(() => {
+                        if (indexLOD !== materialLODs.length - 1) {
+                            const materialIndex = materialLODs[indexLOD + 1]._index;
+                            this._loadMaterialSignals[materialIndex].resolve();
+                            delete this._loadMaterialSignals[materialIndex];
+                        }
                     });
-                }, this.Delay);
-            });
-        }
 
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean {
-            return this._loadExtension<IMSFTLOD>(context, material, (context, extension, onComplete) => {
-                const materials = [material];
-                for (let index of extension.ids) {
-                    const lodMaterial = GLTFLoader._GetProperty(loader._gltf.materials, index);
-                    if (!lodMaterial) {
-                        throw new Error(context + ": Failed to find material " + index);
+                    if (indexLOD === 0) {
+                        firstPromise = promise;
+                    }
+                    else {
+                        this._loader._completePromises.push(promise);
+                        this._loadingMaterialLOD = null;
                     }
-
-                    materials.push(lodMaterial);
                 }
 
-                loader._addLoaderPendingData(material);
-                this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, () => {
-                    loader._removeLoaderPendingData(material);
-                    onComplete();
-                });
+                return firstPromise!;
             });
         }
 
-        private _loadMaterialLOD(loader: GLTFLoader, context: string, materials: IGLTFMaterial[], index: number, assign: (babylonMaterial: Material, isNew: boolean) => void, onComplete: () => void): void {
-            loader._loadMaterial(context, materials[index], (babylonMaterial, isNew) => {
-                if (index === materials.length - 1) {
-                    assign(babylonMaterial, isNew);
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>> {
+            // Defer the loading of uris if loading a material or node LOD.
+            if (this._loadingMaterialLOD) {
+                const index = this._loadingMaterialLOD._index;
+                return this._loadMaterialSignals[index].promise.then(() => {
+                    return this._loader._loadUriAsync(context, uri);
+                });
+            }
+            else if (this._loadingNodeLOD) {
+                const index = this._loadingNodeLOD._index;
+                return this._loadNodeSignals[index].promise.then(() => {
+                    return this._loader._loadUriAsync(context, uri);
+                });
+            }
 
-                    // Load the next LOD when the loader is ready to render.
-                    loader._executeWhenRenderReady(() => {
-                        this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
-                    });
-                }
-                else {
-                    BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), () => {
-                        assign(babylonMaterial, isNew);
+            return null;
+        }
 
-                        if (index === 0) {
-                            onComplete();
-                        }
-                        else {
-                            setTimeout(() => {
-                                loader._tryCatchOnError(() => {
-                                    this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
-                                });
-                            }, this.Delay);
-                        }
-                    });
-                }
-            });
+        /**
+         * Gets an array of LOD properties from lowest to highest.
+         */
+        private static _GetLODs<T>(context: string, property: T, array: ArrayLike<T> | undefined, ids: number[]): T[] {
+            const properties = [property];
+            for (const id of ids) {
+                properties.push(GLTFLoader._GetProperty(context + "/ids/" + id, array, id));
+            }
+
+            return properties.reverse();
         }
     }
 
-    GLTFLoader.RegisterExtension(new MSFTLOD());
-}
+    GLTFLoader._Register(NAME, loader => new MSFTLOD(loader));
+}

File diff suppressed because it is too large
+ 876 - 1178
loaders/src/glTF/2.0/babylon.glTFLoader.ts


+ 41 - 49
loaders/src/glTF/2.0/babylon.glTFLoaderExtension.ts

@@ -2,80 +2,72 @@
 
 module BABYLON.GLTF2 {
     export abstract class GLTFLoaderExtension {
-        public enabled: boolean = true;
+        public enabled = true;
 
-        public abstract get name(): string;
+        protected _loader: GLTFLoader;
 
-        protected _traverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean { return false; }
+        constructor(loader: GLTFLoader) {
+            this._loader = loader;
+        }
+
+        protected abstract get _name(): string;
+
+        // #region Overridable Methods
+
+        /** Override this method to modify the default behavior for loading scenes. */
+        protected _loadSceneAsync(context: string, node: ILoaderScene): Nullable<Promise<void>> { return null; }
 
-        protected _loadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean { return false; }
+        /** Override this method to modify the default behavior for loading nodes. */
+        protected _loadNodeAsync(context: string, node: ILoaderNode): Nullable<Promise<void>> { return null; }
 
-        protected _loadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean { return false; }
+        /** Override this method to modify the default behavior for loading materials. */
+        protected _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>> { return null; }
 
-        protected _loadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean { return false; }
+        /** Override this method to modify the default behavior for loading uris. */
+        protected _loadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>> { return null; }
 
-        protected _loadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean { return false; }
+        // #endregion
 
-        protected _loadExtension<T>(context: string, property: IGLTFProperty, action: (context: string, extension: T, onComplete: () => void) => void): boolean {
+        /** Helper method called by a loader extension to load an glTF extension. */
+        protected _loadExtensionAsync<T>(context: string, property: IProperty, actionAsync: (context: string, extension: T) => Promise<void>): Nullable<Promise<void>> {
             if (!property.extensions) {
-                return false;
+                return null;
             }
 
-            const extension = property.extensions[this.name] as T;
+            const extensions = property.extensions;
+
+            const extension = extensions[this._name] as T;
             if (!extension) {
-                return false;
+                return null;
             }
 
             // Clear out the extension before executing the action to avoid recursing into the same property.
-            property.extensions[this.name] = undefined;
+            delete extensions[this._name];
 
-            action(context + "extensions/" + this.name, extension, () => {
+            return actionAsync(context + "extensions/" + this._name, extension).then(() => {
                 // Restore the extension after completing the action.
-                property.extensions![this.name] = extension;
+                extensions[this._name] = extension;
             });
-
-            return true;
-        }
-
-        //
-        // Utilities
-        //
-
-        public static _Extensions: GLTFLoaderExtension[] = [];
-
-        public static TraverseNode(loader: GLTFLoader, context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): boolean {
-            return this._ApplyExtensions(extension => extension._traverseNode(loader, context, node, action, parentNode));
-        }
-
-        public static LoadRoot(loader: GLTFLoader, context: string, root: BABYLON.GLTF2._IGLTF): boolean {
-            return this._ApplyExtensions(extension => extension._loadRoot(loader, context, root));
         }
 
-        public static LoadScene(loader: GLTFLoader, context: string, scene: IGLTFScene): boolean {
-            return this._ApplyExtensions(extension => extension._loadScene(loader, context, scene));
+        /** Helper method called by the loader to allow extensions to override loading scenes. */
+        public static _LoadSceneAsync(loader: GLTFLoader, context: string, scene: ILoaderScene): Nullable<Promise<void>> {
+            return loader._applyExtensions(extension => extension._loadSceneAsync(context, scene));
         }
 
-        public static LoadNode(loader: GLTFLoader, context: string, node: IGLTFNode): boolean {
-            return this._ApplyExtensions(extension => extension._loadNode(loader, context, node));
+        /** Helper method called by the loader to allow extensions to override loading nodes. */
+        public static _LoadNodeAsync(loader: GLTFLoader, context: string, node: ILoaderNode): Nullable<Promise<void>> {
+            return loader._applyExtensions(extension => extension._loadNodeAsync(context, node));
         }
 
-        public static LoadMaterial(loader: GLTFLoader, context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): boolean {
-            return this._ApplyExtensions(extension => extension._loadMaterial(loader, context, material, assign));
+        /** Helper method called by the loader to allow extensions to override loading materials. */
+        public static _LoadMaterialAsync(loader: GLTFLoader, context: string, material: ILoaderMaterial, babylonMesh: Mesh): Nullable<Promise<void>> {
+            return loader._applyExtensions(extension => extension._loadMaterialAsync(context, material, babylonMesh));
         }
 
-        private static _ApplyExtensions(action: (extension: GLTFLoaderExtension) => boolean) {
-            const extensions = GLTFLoaderExtension._Extensions;
-            if (!extensions) {
-                return false;
-            }
-
-            for (const extension of extensions) {
-                if (extension.enabled && action(extension)) {
-                    return true;
-                }
-            }
-
-            return false;
+        /** Helper method called by the loader to allow extensions to override loading uris. */
+        public static _LoadUriAsync(loader: GLTFLoader, context: string, uri: string): Nullable<Promise<ArrayBufferView>> {
+            return loader._applyExtensions(extension => extension._loadUriAsync(context, uri));
         }
     }
 }

+ 57 - 260
loaders/src/glTF/2.0/babylon.glTFLoaderInterfaces.ts

@@ -1,306 +1,103 @@
 /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
+/// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
 
 module BABYLON.GLTF2 {
-    /**
-    * Enums
-    */
-    export enum EComponentType {
-        BYTE = 5120,
-        UNSIGNED_BYTE = 5121,
-        SHORT = 5122,
-        UNSIGNED_SHORT = 5123,
-        UNSIGNED_INT = 5125,
-        FLOAT = 5126
+    export interface ILoaderAccessor extends IAccessor, IArrayItem {
+        _data?: Promise<TypedArray>;
     }
 
-    export enum EMeshPrimitiveMode {
-        POINTS = 0,
-        LINES = 1,
-        LINE_LOOP = 2,
-        LINE_STRIP = 3,
-        TRIANGLES = 4,
-        TRIANGLE_STRIP = 5,
-        TRIANGLE_FAN = 6
+    export interface ILoaderAnimationChannel extends IAnimationChannel, IArrayItem {
+        _babylonAnimationGroup: AnimationGroup;
     }
 
-    export enum ETextureMagFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
+    export interface ILoaderAnimationSamplerData {
+        input: Float32Array;
+        interpolation: AnimationSamplerInterpolation;
+        output: Float32Array;
     }
 
-    export enum ETextureMinFilter {
-        NEAREST = 9728,
-        LINEAR = 9729,
-        NEAREST_MIPMAP_NEAREST = 9984,
-        LINEAR_MIPMAP_NEAREST = 9985,
-        NEAREST_MIPMAP_LINEAR = 9986,
-        LINEAR_MIPMAP_LINEAR = 9987
+    export interface ILoaderAnimationSampler extends IAnimationSampler, IArrayItem {
+        _data: Promise<ILoaderAnimationSamplerData>;
     }
 
-    export enum ETextureWrapMode {
-        CLAMP_TO_EDGE = 33071,
-        MIRRORED_REPEAT = 33648,
-        REPEAT = 10497
-    }
-
-    /**
-    * Interfaces
-    */
-    export interface IGLTFProperty {
-        extensions?: { [key: string]: any };
-        extras?: any;
-    }
-
-    export interface IGLTFChildRootProperty extends IGLTFProperty {
-        name?: string;
-    }
-
-    export interface IGLTFAccessorSparseIndices extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-    }
-
-    export interface IGLTFAccessorSparseValues extends IGLTFProperty {
-        bufferView: number;
-        byteOffset?: number;
-    }
-
-    export interface IGLTFAccessorSparse extends IGLTFProperty {
-        count: number;
-        indices: IGLTFAccessorSparseIndices;
-        values: IGLTFAccessorSparseValues;
-    }
-
-    export interface IGLTFAccessor extends IGLTFChildRootProperty {
-        bufferView?: number;
-        byteOffset?: number;
-        componentType: EComponentType;
-        normalized?: boolean;
-        count: number;
-        type: string;
-        max: number[];
-        min: number[];
-        sparse?: IGLTFAccessorSparse;
-
-        // Runtime values
-        index: number;
-    }
-
-    export interface IGLTFAnimationChannel extends IGLTFProperty {
-        sampler: number;
-        target: IGLTFAnimationChannelTarget;
-    }
-
-    export interface IGLTFAnimationChannelTarget extends IGLTFProperty {
-        node: number;
-        path: string;
-    }
-
-    export interface IGLTFAnimationSampler extends IGLTFProperty {
-        input: number;
-        interpolation?: string;
-        output: number;
-    }
-
-    export interface IGLTFAnimation extends IGLTFChildRootProperty {
-        channels: IGLTFAnimationChannel[];
-        samplers: IGLTFAnimationSampler[];
-
-        // Runtime values
-        index: number;
-        babylonAnimationGroup: AnimationGroup;
-    }
-
-    export interface IGLTFAsset extends IGLTFChildRootProperty {
-        copyright?: string;
-        generator?: string;
-        version: string;
-        minVersion?: string;
-    }
-
-    export interface IGLTFBuffer extends IGLTFChildRootProperty {
-        uri?: string;
-        byteLength: number;
-
-        // Runtime values
-        index: number;
-        loadedData?: ArrayBufferView;
-        loadedObservable?: Observable<IGLTFBuffer>;
-    }
-
-    export interface IGLTFBufferView extends IGLTFChildRootProperty {
-        buffer: number;
-        byteOffset?: number;
-        byteLength: number;
-        byteStride?: number;
-
-        // Runtime values
-        index: number;
-    }
-
-    export interface IGLTFCameraOrthographic extends IGLTFProperty {
-        xmag: number;
-        ymag: number;
-        zfar: number;
-        znear: number;
-    }
+    export interface ILoaderAnimation extends IAnimation, IArrayItem {
+        channels: ILoaderAnimationChannel[];
+        samplers: ILoaderAnimationSampler[];
 
-    export interface IGLTFCameraPerspective extends IGLTFProperty {
-        aspectRatio: number;
-        yfov: number;
-        zfar: number;
-        znear: number;
+        _babylonAnimationGroup: Nullable<AnimationGroup>;
     }
 
-    export interface IGLTFCamera extends IGLTFChildRootProperty {
-        orthographic?: IGLTFCameraOrthographic;
-        perspective?: IGLTFCameraPerspective;
-        type: string;
+    export interface ILoaderBuffer extends IBuffer, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
 
-    export interface IGLTFImage extends IGLTFChildRootProperty {
-        uri?: string;
-        mimeType?: string;
-        bufferView?: number;
-
-        // Runtime values
-        index: number;
+    export interface ILoaderBufferView extends IBufferView, IArrayItem {
+        _data?: Promise<ArrayBufferView>;
     }
 
-    export interface IGLTFMaterialNormalTextureInfo extends IGLTFTextureInfo {
-        scale: number;
+    export interface ILoaderCamera extends ICamera, IArrayItem {
     }
 
-    export interface IGLTFMaterialOcclusionTextureInfo extends IGLTFTextureInfo {
-        strength: number;
+    export interface ILoaderImage extends IImage, IArrayItem {
+        _objectURL?: Promise<string>;
     }
 
-    export interface IGLTFMaterialPbrMetallicRoughness {
-        baseColorFactor: number[];
-        baseColorTexture: IGLTFTextureInfo;
-        metallicFactor: number;
-        roughnessFactor: number;
-        metallicRoughnessTexture: IGLTFTextureInfo;
+    export interface ILoaderMaterial extends IMaterial, IArrayItem {
+        _babylonMaterial?: Material;
+        _babylonMeshes?: AbstractMesh[];
+        _loaded?: Promise<void>;
     }
 
-    export interface IGLTFMaterial extends IGLTFChildRootProperty {
-        pbrMetallicRoughness?: IGLTFMaterialPbrMetallicRoughness;
-        normalTexture?: IGLTFMaterialNormalTextureInfo;
-        occlusionTexture?: IGLTFMaterialOcclusionTextureInfo;
-        emissiveTexture?: IGLTFTextureInfo;
-        emissiveFactor?: number[];
-        alphaMode?: string;
-        alphaCutoff: number;
-        doubleSided?: boolean;
-
-        // Runtime values
-        index: number;
-        babylonMaterial: Material;
+    export interface ILoaderMesh extends IMesh, IArrayItem {
+        primitives: ILoaderMeshPrimitive[];
     }
 
-    export interface IGLTFMeshPrimitive extends IGLTFProperty {
-        attributes: { [name: string]: number };
-        indices?: number;
-        material?: number;
-        mode?: EMeshPrimitiveMode;
-        targets?: { [name: string]: number }[];
-
-        // Runtime values
-        vertexData: VertexData;
-        targetsVertexData: VertexData[];
+    export interface ILoaderMeshPrimitive extends IMeshPrimitive, IArrayItem {
     }
 
-    export interface IGLTFMesh extends IGLTFChildRootProperty {
-        primitives: IGLTFMeshPrimitive[];
-        weights?: number[];
-
-        // Runtime values
-        index: number;
-        hasVertexAlpha: boolean;
+    export interface ILoaderNode extends INode, IArrayItem {
+        _parent: ILoaderNode;
+        _babylonMesh?: Mesh;
+        _primitiveBabylonMeshes?: Mesh[];
+        _babylonAnimationTargets?: Node[];
+        _numMorphTargets?: number;
     }
 
-    export interface IGLTFNode extends IGLTFChildRootProperty {
-        camera?: number;
-        children?: number[];
-        skin?: number;
-        matrix?: number[];
-        mesh?: number;
-        rotation?: number[];
-        scale?: number[];
-        translation?: number[];
-        weights?: number[];
-
-        // Runtime values
-        index: number;
-        parent: IGLTFNode;
-        babylonMesh: Mesh;
-        babylonAnimationTargets?: Node[];
-    }
-
-    export interface IGLTFSampler extends IGLTFChildRootProperty {
-        magFilter?: ETextureMagFilter;
-        minFilter?: ETextureMinFilter;
-        wrapS?: ETextureWrapMode;
-        wrapT?: ETextureWrapMode;
-
-        // Runtime values
-        index: number;
+    export interface ILoaderSamplerData {
         noMipMaps: boolean;
         samplingMode: number;
         wrapU: number;
         wrapV: number;
     }
 
-    export interface IGLTFScene extends IGLTFChildRootProperty {
-        nodes: number[];
-
-        // Runtime values
-        index: number;
+    export interface ILoaderSampler extends ISampler, IArrayItem {
+        _data?: ILoaderSamplerData;
     }
 
-    export interface IGLTFSkin extends IGLTFChildRootProperty {
-        inverseBindMatrices?: number;
-        skeleton?: number;
-        joints: number[];
-
-        // Runtime values
-        index: number;
-        babylonSkeleton: Skeleton;
+    export interface ILoaderScene extends IScene, IArrayItem {
     }
 
-    export interface IGLTFTexture extends IGLTFChildRootProperty {
-        sampler?: number;
-        source: number;
-
-        // Runtime values
-        index: number;
-        url?: string;
-        dataReadyObservable?: Observable<IGLTFTexture>;
+    export interface ILoaderSkin extends ISkin, IArrayItem {
+        _babylonSkeleton: Nullable<Skeleton>;
+        _loaded?: Promise<void>;
     }
 
-    export interface IGLTFTextureInfo {
-        index: number;
-        texCoord?: number;
+    export interface ILoaderTexture extends ITexture, IArrayItem {
     }
 
-    export interface _IGLTF extends IGLTFProperty {
-        accessors?: IGLTFAccessor[];
-        animations?: IGLTFAnimation[];
-        asset: IGLTFAsset;
-        buffers?: IGLTFBuffer[];
-        bufferViews?: IGLTFBufferView[];
-        cameras?: IGLTFCamera[];
-        extensionsUsed?: string[];
-        extensionsRequired?: string[];
-        images?: IGLTFImage[];
-        materials?: IGLTFMaterial[];
-        meshes?: IGLTFMesh[];
-        nodes?: IGLTFNode[];
-        samplers?: IGLTFSampler[];
-        scene?: number;
-        scenes?: IGLTFScene[];
-        skins?: IGLTFSkin[];
-        textures?: IGLTFTexture[];
+    export interface ILoaderGLTF extends IGLTF {
+        accessors?: ILoaderAccessor[];
+        animations?: ILoaderAnimation[];
+        buffers?: ILoaderBuffer[];
+        bufferViews?: ILoaderBufferView[];
+        cameras?: ILoaderCamera[];
+        images?: ILoaderImage[];
+        materials?: ILoaderMaterial[];
+        meshes?: ILoaderMesh[];
+        nodes?: ILoaderNode[];
+        samplers?: ILoaderSampler[];
+        scenes?: ILoaderScene[];
+        skins?: ILoaderSkin[];
+        textures?: ILoaderTexture[];
     }
 }

+ 21 - 0
loaders/src/glTF/2.0/babylon.glTFLoaderUtilities.ts

@@ -0,0 +1,21 @@
+/// <reference path="../../../../dist/preview release/babylon.d.ts"/>
+
+module BABYLON.GLTF2 {
+    export interface TypedArray extends ArrayBufferView {
+        [index: number]: number;
+    }
+
+    export interface IArrayItem {
+        _index: number;
+    }
+
+    export class ArrayItem {
+        public static Assign(values?: IArrayItem[]): void {
+            if (values) {
+                for (let index = 0; index < values.length; index++) {
+                    values[index]._index = index;
+                }
+            }
+        }
+    }
+}

+ 0 - 36
loaders/src/glTF/2.0/babylon.glTFLoaderUtils.ts

@@ -1,36 +0,0 @@
-/// <reference path="../../../../dist/preview release/babylon.d.ts"/>
-
-module BABYLON.GLTF2 {
-    /**
-    * Utils functions for GLTF
-    */
-    export class GLTFUtils {
-        /**
-        * If the uri is a base64 string
-        * @param uri: the uri to test
-        */
-        public static IsBase64(uri: string): boolean {
-            return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
-        }
-
-        /**
-        * Decode the base64 uri
-        * @param uri: the uri to decode
-        */
-        public static DecodeBase64(uri: string): ArrayBuffer {
-            const decodedString = atob(uri.split(",")[1]);
-            const bufferLength = decodedString.length;
-            const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
-
-            for (let i = 0; i < bufferLength; i++) {
-                bufferView[i] = decodedString.charCodeAt(i);
-            }
-
-            return bufferView.buffer;
-        }
-
-        public static ValidateUri(uri: string): boolean {
-            return (uri.indexOf("..") === -1);
-        }
-    }
-}

+ 55 - 48
loaders/src/glTF/babylon.glTFFileLoader.ts

@@ -35,6 +35,20 @@ module BABYLON {
         bin: Nullable<ArrayBufferView>;
     }
 
+    export enum GLTFLoaderState {
+        Loading,
+        Ready,
+        Complete
+    }
+
+    export interface IGLTFLoaderExtension {
+        enabled: boolean;
+    }
+
+    export interface IGLTFLoaderExtensions {
+        [name: string]: IGLTFLoaderExtension;
+    }
+
     export interface IGLTFLoader extends IDisposable {
         coordinateSystemMode: GLTFLoaderCoordinateSystemMode;
         animationStartMode: GLTFLoaderAnimationStartMode;
@@ -48,8 +62,11 @@ module BABYLON {
         onMaterialLoadedObservable: Observable<Material>;
         onCompleteObservable: Observable<IGLTFLoader>;
 
-        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+        state: Nullable<GLTFLoaderState>;
+        extensions: Nullable<IGLTFLoaderExtensions>;
+
+        importMeshAsync: (meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }>;
+        loadAsync: (scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void) => Promise<void>;
     }
 
     export class GLTFFileLoader implements IDisposable, ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
@@ -113,7 +130,7 @@ module BABYLON {
         /**
          * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
          */
-        public onMeshLoadedObservable = new Observable<AbstractMesh>();
+        public readonly onMeshLoadedObservable = new Observable<AbstractMesh>();
 
         private _onMeshLoadedObserver: Nullable<Observer<AbstractMesh>>;
         public set onMeshLoaded(callback: (mesh: AbstractMesh) => void) {
@@ -126,7 +143,7 @@ module BABYLON {
         /**
          * Raised when the loader creates a texture after parsing the glTF properties of the texture.
          */
-        public onTextureLoadedObservable = new Observable<BaseTexture>();
+        public readonly onTextureLoadedObservable = new Observable<BaseTexture>();
 
         private _onTextureLoadedObserver: Nullable<Observer<BaseTexture>>;
         public set onTextureLoaded(callback: (Texture: BaseTexture) => void) {
@@ -139,7 +156,7 @@ module BABYLON {
         /**
          * Raised when the loader creates a material after parsing the glTF properties of the material.
          */
-        public onMaterialLoadedObservable = new Observable<Material>();
+        public readonly onMaterialLoadedObservable = new Observable<Material>();
 
         private _onMaterialLoadedObserver: Nullable<Observer<Material>>;
         public set onMaterialLoaded(callback: (Material: Material) => void) {
@@ -154,7 +171,7 @@ module BABYLON {
          * For assets with LODs, raised when all of the LODs are complete.
          * For assets without LODs, raised when the model is complete, immediately after onSuccess.
          */
-        public onCompleteObservable = new Observable<GLTFFileLoader>();
+        public readonly onCompleteObservable = new Observable<GLTFFileLoader>();
 
         private _onCompleteObserver: Nullable<Observer<GLTFFileLoader>>;
         public set onComplete(callback: () => void) {
@@ -167,7 +184,7 @@ module BABYLON {
         /**
         * Raised when the loader is disposed.
         */
-        public onDisposeObservable = new Observable<GLTFFileLoader>();
+        public readonly onDisposeObservable = new Observable<GLTFFileLoader>();
 
         private _onDisposeObserver: Nullable<Observer<GLTFFileLoader>>;
         public set onDispose(callback: () => void) {
@@ -177,6 +194,20 @@ module BABYLON {
             this._onDisposeObserver = this.onDisposeObservable.add(callback);
         }
 
+        /**
+         * The loader state or null if not active.
+         */
+        public get loaderState(): Nullable<GLTFLoaderState> {
+            return this._loader ? this._loader.state : null;
+        }
+
+        /**
+         * The loader extensions or null if not active.
+         */
+        public get loaderExtensions(): Nullable<IGLTFLoaderExtensions> {
+            return this._loader ? this._loader.extensions : null;
+        }
+
         // #endregion
 
         private _loader: Nullable<IGLTFLoader> = null;
@@ -207,59 +238,35 @@ module BABYLON {
             this.onDisposeObservable.clear();
         }
 
-        public importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
-            try {
+        public importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }> {
+            return Promise.resolve().then(() => {
                 const loaderData = this._parse(data);
                 this._loader = this._getLoader(loaderData);
-                this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    Tools.Error(e.message);
-                }
-            }
+                return this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
+            });
         }
 
-        public loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
-            try {
+        public loadAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void> {
+            return Promise.resolve().then(() => {
                 const loaderData = this._parse(data);
                 this._loader = this._getLoader(loaderData);
-                this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    Tools.Error(e.message);
-                }
-            }
+                return this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
+            });
         }
 
-        public loadAssetsAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onSuccess: (assets:AssetContainer) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
-            try {
+        public loadAssetContainerAsync(scene: Scene, data: string | ArrayBuffer, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer> {
+            return Promise.resolve().then(() => {
                 const loaderData = this._parse(data);
                 this._loader = this._getLoader(loaderData);
-                this._loader.importMeshAsync(null, scene, loaderData, rootUrl,  (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => {
+                return this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(result => {
                     var container = new AssetContainer(scene);
-                    Array.prototype.push.apply(container.meshes, meshes)
-                    Array.prototype.push.apply(container.particleSystems, particleSystems)
-                    Array.prototype.push.apply(container.skeletons, skeletons)
+                    Array.prototype.push.apply(container.meshes, result.meshes);
+                    Array.prototype.push.apply(container.particleSystems, result.particleSystems);
+                    Array.prototype.push.apply(container.skeletons, result.skeletons);
                     container.removeAllFromScene();
-                    onSuccess(container)
-                }, onProgress, onError);
-            }
-            catch (e) {
-                if (onError) {
-                    onError(e.message, e);
-                }
-                else {
-                    Tools.Error(e.message);
-                }
-            }
+                    return container;
+                });
+            });
         }
 
         public canDirectLoad(data: string): boolean {

+ 1 - 1
package.json

@@ -9,7 +9,7 @@
     ],
     "name": "babylonjs",
     "description": "Babylon.js is a JavaScript 3D engine based on webgl.",
-    "version": "3.2.0-alpha6",
+    "version": "3.2.0-alpha7",
     "repository": {
         "type": "git",
         "url": "https://github.com/BabylonJS/Babylon.js.git"

+ 0 - 4
sandbox/index.js

@@ -36,10 +36,6 @@ if (BABYLON.Engine.isSupported()) {
     BABYLON.GLTFFileLoader.IncrementalLoading = false;
     BABYLON.SceneLoader.OnPluginActivatedObservable.add(function (plugin) {
         currentPluginName = plugin.name;
-
-        if (plugin.name === "gltf" && plugin instanceof BABYLON.GLTFFileLoader) {
-            plugin.compileMaterials = true;
-        }
     });
 
     // Resize

+ 8 - 3
src/Engine/babylon.engine.ts

@@ -540,7 +540,7 @@
         }
 
         public static get Version(): string {
-            return "3.2.0-alpha6";
+            return "3.2.0-alpha7";
         }
 
         // Updatable statics so stick with vars here
@@ -2626,8 +2626,13 @@
             var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
             if (this._compiledEffects[name]) {
                 var compiledEffect = <Effect>this._compiledEffects[name];
-                if (onCompiled && compiledEffect.isReady()) {
-                    onCompiled(compiledEffect);
+                if (onCompiled) {
+                    if (compiledEffect.isReady()) {
+                        onCompiled(compiledEffect);
+                    }
+                    else {
+                        compiledEffect.onCompileObservable.add(onCompiled, undefined, undefined, true);
+                    }
                 }
                 return compiledEffect;
             }

+ 94 - 0
src/Helpers/babylon.videoDome.ts

@@ -0,0 +1,94 @@
+module BABYLON {
+    /**
+     * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
+     * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
+     * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
+     * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
+     */
+    export class VideoDome extends Node {
+
+        /**
+         * The video texture being displayed on the sphere
+         */
+        protected _videoTexture: VideoTexture;
+
+        /**
+         * The skybox material
+         */
+        protected _material: BackgroundMaterial;
+
+        /**
+         * The surface used for the skybox
+         */
+        protected _mesh: Mesh;
+
+        /**
+         * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
+         * Also see the options.resolution property.
+         */
+        public get fovMultiplier(): number {
+            return this._material.fovMultiplier;
+        }
+        public set fovMultiplier(value: number) {
+            this._material.fovMultiplier = value;
+        }
+
+        /**
+         * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
+         * @param name Element's name, child elements will append suffixes for their own names.
+         * @param urlsOrVideo
+         * @param options An object containing optional or exposed sub element properties:
+         * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
+         * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
+         * @param options **autoPlay=true** Automatically attempt to being playing the video.
+         * @param options **loop=true** Automatically loop video on end.
+         * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
+         */
+        constructor(name: string, urlsOrVideo: string | string[] | HTMLVideoElement, options: {
+            resolution?: number,
+            clickToPlay?: boolean,
+            autoPlay?: boolean,
+            loop?: boolean,
+            size?: number
+        }, scene: Scene) {
+            super(name, scene);
+
+            // set defaults and manage values
+            name = name || "videoDome";
+            options.resolution = (Math.abs(options.resolution as any) | 0) || 12;
+            options.clickToPlay = Boolean(options.clickToPlay);
+            options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
+            options.loop = options.loop === undefined ? true : Boolean(options.loop);
+            options.size = Math.abs(options.size as any) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
+
+            // create
+            let tempOptions:VideoTextureSettings = {loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true};
+            let material = this._material = new BABYLON.BackgroundMaterial(name+"_material", scene);
+            let texture = this._videoTexture = new BABYLON.VideoTexture(name+"_texture", urlsOrVideo, scene, false, false, Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
+            this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name+"_mesh", {
+                flat: false, // saves on vertex data
+                radius: options.size,
+                subdivisions: options.resolution,
+                sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
+            }, scene);
+
+            // configure material
+            texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
+            texture.wrapV = Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
+            material.reflectionTexture = this._videoTexture;
+            material.useEquirectangularFOV = true;
+            material.fovMultiplier = 1.0;
+
+            // configure mesh
+            this._mesh.material = material;
+            this._mesh.parent = this;
+
+            // optional configuration
+            if(options.clickToPlay) {
+                scene.onPointerUp = () => {
+                    this._videoTexture.video.play();
+                }
+            }
+        }
+    }
+}

+ 20 - 0
src/Lights/Shadows/babylon.shadowGenerator.ts

@@ -57,6 +57,13 @@
         forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ useInstances: boolean }>): void;
 
         /**
+         * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
+         * @param options Sets of optional options forcing the compilation with different modes 
+         * @returns A promise that resolves when the compilation completes
+         */
+        forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void>;
+
+        /**
          * Serializes the shadow generator setup to a json object.
          * @returns The serialized JSON object 
          */
@@ -846,6 +853,19 @@
         }
 
         /**
+         * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
+         * @param options Sets of optional options forcing the compilation with different modes 
+         * @returns A promise that resolves when the compilation completes
+         */
+        public forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void> {
+            return new Promise(resolve => {
+                this.forceCompilation(() => {
+                    resolve();
+                }, options);
+            });
+        }
+
+        /**
          * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
          * @param subMesh The submesh we want to render in the shadow map
          * @param useInstances Defines wether will draw in the map using instances

+ 299 - 298
src/Loading/Plugins/babylon.babylonFileLoader.ts

@@ -28,355 +28,352 @@
         return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
     }
 
-    var loadAssets = (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void, addToScene = false):Nullable<AssetContainer> => {
+    var loadAssetContainer = (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void, addToScene = false): AssetContainer => {
         var container = new AssetContainer(scene);
 
-            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
-            // when SceneLoader.debugLogging = true (default), or exception encountered.
-            // Everything stored in var log instead of writing separate lines to support only writing in exception,
-            // and avoid problems with multiple concurrent .babylon loads.
-            var log = "importScene has failed JSON parse";
-            try {
-                var parsedData = JSON.parse(data);
-                log = "";
-                var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;               
-
-                var index: number;
-                var cache: number;
-                // Lights
-                if (parsedData.lights !== undefined && parsedData.lights !== null) {
-                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
-                        var parsedLight = parsedData.lights[index];
-                        var light = Light.Parse(parsedLight, scene);
-                        if (light) {
-                            container.lights.push(light);
-                            log += (index === 0 ? "\n\tLights:" : "");
-                            log += "\n\t\t" + light.toString(fullDetails);
-                        }
+        // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
+        // when SceneLoader.debugLogging = true (default), or exception encountered.
+        // Everything stored in var log instead of writing separate lines to support only writing in exception,
+        // and avoid problems with multiple concurrent .babylon loads.
+        var log = "importScene has failed JSON parse";
+        try {
+            var parsedData = JSON.parse(data);
+            log = "";
+            var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
+
+            var index: number;
+            var cache: number;
+            // Lights
+            if (parsedData.lights !== undefined && parsedData.lights !== null) {
+                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
+                    var parsedLight = parsedData.lights[index];
+                    var light = Light.Parse(parsedLight, scene);
+                    if (light) {
+                        container.lights.push(light);
+                        log += (index === 0 ? "\n\tLights:" : "");
+                        log += "\n\t\t" + light.toString(fullDetails);
                     }
                 }
+            }
 
-                // Animations
-                if (parsedData.animations !== undefined && parsedData.animations !== null) {
-                    for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
-                        var parsedAnimation = parsedData.animations[index];
-                        var animation = Animation.Parse(parsedAnimation);
-                        scene.animations.push(animation);
-                        container.animations.push(animation);
-                        log += (index === 0 ? "\n\tAnimations:" : "");
-                        log += "\n\t\t" + animation.toString(fullDetails);
-                    }
+            // Animations
+            if (parsedData.animations !== undefined && parsedData.animations !== null) {
+                for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
+                    var parsedAnimation = parsedData.animations[index];
+                    var animation = Animation.Parse(parsedAnimation);
+                    scene.animations.push(animation);
+                    container.animations.push(animation);
+                    log += (index === 0 ? "\n\tAnimations:" : "");
+                    log += "\n\t\t" + animation.toString(fullDetails);
                 }
+            }
 
-                // Materials
-                if (parsedData.materials !== undefined && parsedData.materials !== null) {
-                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                        var parsedMaterial = parsedData.materials[index];
-                        var mat = Material.Parse(parsedMaterial, scene, rootUrl);
-                        container.materials.push(mat);
-                        log += (index === 0 ? "\n\tMaterials:" : "");
-                        log += "\n\t\t" + mat.toString(fullDetails);
-                    }
+            // Materials
+            if (parsedData.materials !== undefined && parsedData.materials !== null) {
+                for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                    var parsedMaterial = parsedData.materials[index];
+                    var mat = Material.Parse(parsedMaterial, scene, rootUrl);
+                    container.materials.push(mat);
+                    log += (index === 0 ? "\n\tMaterials:" : "");
+                    log += "\n\t\t" + mat.toString(fullDetails);
                 }
+            }
 
-                if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
-                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
-                        var parsedMultiMaterial = parsedData.multiMaterials[index];
-                        var mmat = Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                        container.multiMaterials.push(mmat);
-                        log += (index === 0 ? "\n\tMultiMaterials:" : "");
-                        log += "\n\t\t" + mmat.toString(fullDetails);
-                    }
+            if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
+                for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
+                    var parsedMultiMaterial = parsedData.multiMaterials[index];
+                    var mmat = Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                    container.multiMaterials.push(mmat);
+                    log += (index === 0 ? "\n\tMultiMaterials:" : "");
+                    log += "\n\t\t" + mmat.toString(fullDetails);
                 }
+            }
 
-                // Morph targets
-                if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
-                    for (var managerData of parsedData.morphTargetManagers) {
-                        container.morphTargetManagers.push(MorphTargetManager.Parse(managerData, scene));
-                    }
+            // Morph targets
+            if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
+                for (var managerData of parsedData.morphTargetManagers) {
+                    container.morphTargetManagers.push(MorphTargetManager.Parse(managerData, scene));
                 }
+            }
 
-                // Skeletons
-                if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
-                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
-                        var parsedSkeleton = parsedData.skeletons[index];
-                        var skeleton = Skeleton.Parse(parsedSkeleton, scene);
-                        container.skeletons.push(skeleton);
-                        log += (index === 0 ? "\n\tSkeletons:" : "");
-                        log += "\n\t\t" + skeleton.toString(fullDetails);
-                    }
+            // Skeletons
+            if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
+                for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
+                    var parsedSkeleton = parsedData.skeletons[index];
+                    var skeleton = Skeleton.Parse(parsedSkeleton, scene);
+                    container.skeletons.push(skeleton);
+                    log += (index === 0 ? "\n\tSkeletons:" : "");
+                    log += "\n\t\t" + skeleton.toString(fullDetails);
                 }
+            }
 
-                // Geometries
-                var geometries = parsedData.geometries;
-                if (geometries !== undefined && geometries !== null) {
-                    var addedGeometry = new Array<Nullable<Geometry>>();
-                    // Boxes
-                    var boxes = geometries.boxes;
-                    if (boxes !== undefined && boxes !== null) {
-                        for (index = 0, cache = boxes.length; index < cache; index++) {
-                            var parsedBox = boxes[index];
-                            addedGeometry.push(BoxGeometry.Parse(parsedBox, scene));
-                        }
+            // Geometries
+            var geometries = parsedData.geometries;
+            if (geometries !== undefined && geometries !== null) {
+                var addedGeometry = new Array<Nullable<Geometry>>();
+                // Boxes
+                var boxes = geometries.boxes;
+                if (boxes !== undefined && boxes !== null) {
+                    for (index = 0, cache = boxes.length; index < cache; index++) {
+                        var parsedBox = boxes[index];
+                        addedGeometry.push(BoxGeometry.Parse(parsedBox, scene));
                     }
+                }
 
-                    // Spheres
-                    var spheres = geometries.spheres;
-                    if (spheres !== undefined && spheres !== null) {
-                        for (index = 0, cache = spheres.length; index < cache; index++) {
-                            var parsedSphere = spheres[index];
-                            addedGeometry.push(SphereGeometry.Parse(parsedSphere, scene));
-                        }
+                // Spheres
+                var spheres = geometries.spheres;
+                if (spheres !== undefined && spheres !== null) {
+                    for (index = 0, cache = spheres.length; index < cache; index++) {
+                        var parsedSphere = spheres[index];
+                        addedGeometry.push(SphereGeometry.Parse(parsedSphere, scene));
                     }
+                }
 
-                    // Cylinders
-                    var cylinders = geometries.cylinders;
-                    if (cylinders !== undefined && cylinders !== null) {
-                        for (index = 0, cache = cylinders.length; index < cache; index++) {
-                            var parsedCylinder = cylinders[index];
-                            addedGeometry.push(CylinderGeometry.Parse(parsedCylinder, scene));
-                        }
+                // Cylinders
+                var cylinders = geometries.cylinders;
+                if (cylinders !== undefined && cylinders !== null) {
+                    for (index = 0, cache = cylinders.length; index < cache; index++) {
+                        var parsedCylinder = cylinders[index];
+                        addedGeometry.push(CylinderGeometry.Parse(parsedCylinder, scene));
                     }
+                }
 
-                    // Toruses
-                    var toruses = geometries.toruses;
-                    if (toruses !== undefined && toruses !== null) {
-                        for (index = 0, cache = toruses.length; index < cache; index++) {
-                            var parsedTorus = toruses[index];
-                            addedGeometry.push(TorusGeometry.Parse(parsedTorus, scene));
-                        }
+                // Toruses
+                var toruses = geometries.toruses;
+                if (toruses !== undefined && toruses !== null) {
+                    for (index = 0, cache = toruses.length; index < cache; index++) {
+                        var parsedTorus = toruses[index];
+                        addedGeometry.push(TorusGeometry.Parse(parsedTorus, scene));
                     }
+                }
 
-                    // Grounds
-                    var grounds = geometries.grounds;
-                    if (grounds !== undefined && grounds !== null) {
-                        for (index = 0, cache = grounds.length; index < cache; index++) {
-                            var parsedGround = grounds[index];
-                            addedGeometry.push(GroundGeometry.Parse(parsedGround, scene));
-                        }
+                // Grounds
+                var grounds = geometries.grounds;
+                if (grounds !== undefined && grounds !== null) {
+                    for (index = 0, cache = grounds.length; index < cache; index++) {
+                        var parsedGround = grounds[index];
+                        addedGeometry.push(GroundGeometry.Parse(parsedGround, scene));
                     }
+                }
 
-                    // Planes
-                    var planes = geometries.planes;
-                    if (planes !== undefined && planes !== null) {
-                        for (index = 0, cache = planes.length; index < cache; index++) {
-                            var parsedPlane = planes[index];
-                            addedGeometry.push(PlaneGeometry.Parse(parsedPlane, scene));
-                        }
+                // Planes
+                var planes = geometries.planes;
+                if (planes !== undefined && planes !== null) {
+                    for (index = 0, cache = planes.length; index < cache; index++) {
+                        var parsedPlane = planes[index];
+                        addedGeometry.push(PlaneGeometry.Parse(parsedPlane, scene));
                     }
+                }
 
-                    // TorusKnots
-                    var torusKnots = geometries.torusKnots;
-                    if (torusKnots !== undefined && torusKnots !== null) {
-                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
-                            var parsedTorusKnot = torusKnots[index];
-                            addedGeometry.push(TorusKnotGeometry.Parse(parsedTorusKnot, scene));
-                        }
+                // TorusKnots
+                var torusKnots = geometries.torusKnots;
+                if (torusKnots !== undefined && torusKnots !== null) {
+                    for (index = 0, cache = torusKnots.length; index < cache; index++) {
+                        var parsedTorusKnot = torusKnots[index];
+                        addedGeometry.push(TorusKnotGeometry.Parse(parsedTorusKnot, scene));
                     }
+                }
 
-                    // VertexData
-                    var vertexData = geometries.vertexData;
-                    if (vertexData !== undefined && vertexData !== null) {
-                        for (index = 0, cache = vertexData.length; index < cache; index++) {
-                            var parsedVertexData = vertexData[index];
-                            addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
-                        }
+                // VertexData
+                var vertexData = geometries.vertexData;
+                if (vertexData !== undefined && vertexData !== null) {
+                    for (index = 0, cache = vertexData.length; index < cache; index++) {
+                        var parsedVertexData = vertexData[index];
+                        addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
                     }
+                }
 
-                    addedGeometry.forEach((g)=>{
-                        if(g){
-                            container.geometries.push(g);
-                        }
-                    })
-                }
-                
-                // Transform nodes
-                if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
-                    for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
-                        var parsedTransformNode = parsedData.transformNodes[index];
-                        var node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
-                        container.transformNodes.push(node);
+                addedGeometry.forEach((g) => {
+                    if (g) {
+                        container.geometries.push(g);
                     }
-                }                
+                })
+            }
 
-                // Meshes
-                if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
-                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                        var parsedMesh = parsedData.meshes[index];
-                        var mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
-                        container.meshes.push(mesh);
-                        log += (index === 0 ? "\n\tMeshes:" : "");
-                        log += "\n\t\t" + mesh.toString(fullDetails);
-                    }
+            // Transform nodes
+            if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
+                for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
+                    var parsedTransformNode = parsedData.transformNodes[index];
+                    var node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
+                    container.transformNodes.push(node);
                 }
+            }
 
-                // Cameras
-                if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
-                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
-                        var parsedCamera = parsedData.cameras[index];
-                        var camera = Camera.Parse(parsedCamera, scene);
-                        container.cameras.push(camera);
-                        log += (index === 0 ? "\n\tCameras:" : "");
-                        log += "\n\t\t" + camera.toString(fullDetails);
-                    }
+            // Meshes
+            if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
+                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                    var parsedMesh = parsedData.meshes[index];
+                    var mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
+                    container.meshes.push(mesh);
+                    log += (index === 0 ? "\n\tMeshes:" : "");
+                    log += "\n\t\t" + mesh.toString(fullDetails);
                 }
+            }
 
-                // Browsing all the graph to connect the dots
-                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
-                    var camera = scene.cameras[index];
-                    if (camera._waitingParentId) {
-                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
-                        camera._waitingParentId = null;
-                    }
+            // Cameras
+            if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
+                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
+                    var parsedCamera = parsedData.cameras[index];
+                    var camera = Camera.Parse(parsedCamera, scene);
+                    container.cameras.push(camera);
+                    log += (index === 0 ? "\n\tCameras:" : "");
+                    log += "\n\t\t" + camera.toString(fullDetails);
                 }
+            }
 
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    let light = scene.lights[index];
-                    if (light && light._waitingParentId) {
-                        light.parent = scene.getLastEntryByID(light._waitingParentId);
-                        light._waitingParentId = null;
-                    }
+            // Browsing all the graph to connect the dots
+            for (index = 0, cache = scene.cameras.length; index < cache; index++) {
+                var camera = scene.cameras[index];
+                if (camera._waitingParentId) {
+                    camera.parent = scene.getLastEntryByID(camera._waitingParentId);
+                    camera._waitingParentId = null;
                 }
+            }
 
-                // Sounds
-                // TODO: add sound
-                var loadedSounds: Sound[] = [];
-                var loadedSound: Sound;
-                if (AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
-                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
-                        var parsedSound = parsedData.sounds[index];
-                        if (Engine.audioEngine.canUseWebAudio) {
-                            if (!parsedSound.url) parsedSound.url = parsedSound.name;
-                            if (!loadedSounds[parsedSound.url]) {
-                                loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
-                                loadedSounds[parsedSound.url] = loadedSound;
-                                container.sounds.push(loadedSound);
-                            }
-                            else {
-                                container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
-                            }
-                        } else {
-                            container.sounds.push(new Sound(parsedSound.name, null, scene));
+            for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                let light = scene.lights[index];
+                if (light && light._waitingParentId) {
+                    light.parent = scene.getLastEntryByID(light._waitingParentId);
+                    light._waitingParentId = null;
+                }
+            }
+
+            // Sounds
+            // TODO: add sound
+            var loadedSounds: Sound[] = [];
+            var loadedSound: Sound;
+            if (AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
+                for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
+                    var parsedSound = parsedData.sounds[index];
+                    if (Engine.audioEngine.canUseWebAudio) {
+                        if (!parsedSound.url) parsedSound.url = parsedSound.name;
+                        if (!loadedSounds[parsedSound.url]) {
+                            loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
+                            loadedSounds[parsedSound.url] = loadedSound;
+                            container.sounds.push(loadedSound);
+                        }
+                        else {
+                            container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
                         }
+                    } else {
+                        container.sounds.push(new Sound(parsedSound.name, null, scene));
                     }
                 }
+            }
 
-                loadedSounds = [];
+            loadedSounds = [];
 
-                // Connect parents & children and parse actions
-                for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
-                    var transformNode = scene.transformNodes[index];
-                    if (transformNode._waitingParentId) {
-                        transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
-                        transformNode._waitingParentId = null;
-                    }
-                }                
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var mesh = scene.meshes[index];
-                    if (mesh._waitingParentId) {
-                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
-                        mesh._waitingParentId = null;
-                    }
-                    if (mesh._waitingActions) {
-                        ActionManager.Parse(mesh._waitingActions, mesh, scene);
-                        mesh._waitingActions = null;
-                    }
+            // Connect parents & children and parse actions
+            for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
+                var transformNode = scene.transformNodes[index];
+                if (transformNode._waitingParentId) {
+                    transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
+                    transformNode._waitingParentId = null;
+                }
+            }
+            for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                var mesh = scene.meshes[index];
+                if (mesh._waitingParentId) {
+                    mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
+                    mesh._waitingParentId = null;
+                }
+                if (mesh._waitingActions) {
+                    ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                    mesh._waitingActions = null;
                 }
+            }
 
-                // freeze world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = null;
-                    } else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
+            // freeze world matrix application
+            for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                var currentMesh = scene.meshes[index];
+                if (currentMesh._waitingFreezeWorldMatrix) {
+                    currentMesh.freezeWorldMatrix();
+                    currentMesh._waitingFreezeWorldMatrix = null;
+                } else {
+                    currentMesh.computeWorldMatrix(true);
                 }
+            }
 
-                // Particles Systems
-                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        var ps = ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
-                        container.particleSystems.push(ps);
-                    }
+            // Particles Systems
+            if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
+                for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                    var parsedParticleSystem = parsedData.particleSystems[index];
+                    var ps = ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                    container.particleSystems.push(ps);
                 }
+            }
 
-                // Lens flares
-                if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
-                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
-                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                        var lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
-                        container.lensFlareSystems.push(lf);
-                    }
+            // Lens flares
+            if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
+                for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
+                    var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                    var lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                    container.lensFlareSystems.push(lf);
                 }
+            }
 
-                // Shadows
-                if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
-                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
-                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                        var sg = ShadowGenerator.Parse(parsedShadowGenerator, scene);
-                        container.shadowGenerators.push(sg);
-                    }
+            // Shadows
+            if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
+                for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+                    var parsedShadowGenerator = parsedData.shadowGenerators[index];
+                    var sg = ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                    container.shadowGenerators.push(sg);
                 }
+            }
 
-                // Lights exclusions / inclusions
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    let light = scene.lights[index];
-                    // Excluded check
-                    if (light._excludedMeshesIds.length > 0) {
-                        for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
-                            var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
+            // Lights exclusions / inclusions
+            for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                let light = scene.lights[index];
+                // Excluded check
+                if (light._excludedMeshesIds.length > 0) {
+                    for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
+                        var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
 
-                            if (excludedMesh) {
-                                light.excludedMeshes.push(excludedMesh);
-                            }
+                        if (excludedMesh) {
+                            light.excludedMeshes.push(excludedMesh);
                         }
-
-                        light._excludedMeshesIds = [];
                     }
 
-                    // Included check
-                    if (light._includedOnlyMeshesIds.length > 0) {
-                        for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
-                            var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
+                    light._excludedMeshesIds = [];
+                }
 
-                            if (includedOnlyMesh) {
-                                light.includedOnlyMeshes.push(includedOnlyMesh);
-                            }
-                        }
+                // Included check
+                if (light._includedOnlyMeshesIds.length > 0) {
+                    for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
+                        var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
 
-                        light._includedOnlyMeshesIds = [];
+                        if (includedOnlyMesh) {
+                            light.includedOnlyMeshes.push(includedOnlyMesh);
+                        }
                     }
-                }
 
-                // Actions (scene)
-                if (parsedData.actions !== undefined && parsedData.actions !== null) {
-                    ActionManager.Parse(parsedData.actions, null, scene);
-                }
-                
-                if(!addToScene){
-                    container.removeAllFromScene();
+                    light._includedOnlyMeshesIds = [];
                 }
+            }
 
-                return container;
+            // Actions (scene)
+            if (parsedData.actions !== undefined && parsedData.actions !== null) {
+                ActionManager.Parse(parsedData.actions, null, scene);
+            }
 
-            } catch (err) {
-                let msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
-                if (onError) {
-                    onError(msg, err);
-                } else {
-                    Tools.Log(msg);
-                    throw err;
-                }
-            } finally {
-                if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
-                    Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
-                }
+            if (!addToScene) {
+                container.removeAllFromScene();
             }
+        } catch (err) {
+            let msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
+            if (onError) {
+                onError(msg, err);
+            } else {
+                Tools.Log(msg);
+                throw err;
+            }
+        } finally {
+            if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
+                Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
+            }
+        }
 
-            return null;
+        return container;
     }
 
     SceneLoader.RegisterPlugin({
@@ -481,12 +478,16 @@
                                                 var subMatId = parsedMultiMaterial.materials[matIndex];
                                                 loadedMaterialsIds.push(subMatId);
                                                 var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
-                                                log += "\n\tMaterial " + mat.toString(fullDetails);
+                                                if (mat) {
+                                                    log += "\n\tMaterial " + mat.toString(fullDetails);
+                                                }
                                             }
                                             loadedMaterialsIds.push(parsedMultiMaterial.id);
                                             var mmat = Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                                            materialFound = true;
-                                            log += "\n\tMulti-Material " + mmat.toString(fullDetails);
+                                            if (mmat) {
+                                                materialFound = true;
+                                                log += "\n\tMulti-Material " + mmat.toString(fullDetails);
+                                            }
                                             break;
                                         }
                                     }
@@ -643,26 +644,26 @@
                 }
                 scene.workerCollisions = !!parsedData.workerCollisions;
 
-                var container = loadAssets(scene, data, rootUrl, onerror, true);
-                if(!container){
+                var container = loadAssetContainer(scene, data, rootUrl, onerror, true);
+                if (!container) {
                     return false;
                 }
-                
-                if (parsedData.autoAnimate) {		
-                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);		
+
+                if (parsedData.autoAnimate) {
+                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
                 }
 
-                if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {		
-                    scene.setActiveCameraByID(parsedData.activeCameraID);		
+                if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
+                    scene.setActiveCameraByID(parsedData.activeCameraID);
                 }
 
                 // Environment texture		
-                if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {		
-                    scene.environmentTexture = CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);		
-                    if (parsedData.createDefaultSkybox === true) {		
-                        var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;		
-                        var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;		
-                        scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);		
+                if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
+                    scene.environmentTexture = CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
+                    if (parsedData.createDefaultSkybox === true) {
+                        var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
+                        var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
+                        scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
                     }
                 }
                 // Finish
@@ -682,8 +683,8 @@
             }
             return false;
         },
-        loadAssets: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): Nullable<AssetContainer> =>{
-            var container = loadAssets(scene, data, rootUrl, onerror);
+        loadAssetContainer: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer => {
+            var container = loadAssetContainer(scene, data, rootUrl, onerror);
             return container;
         }
     });

+ 224 - 33
src/Loading/babylon.sceneLoader.ts

@@ -21,23 +21,112 @@
     }
 
     export interface ISceneLoaderPlugin {
+        /**
+         * The friendly name of this plugin.
+         */
         name: string;
+
+        /**
+         * The file extensions supported by this plugin.
+         */
         extensions: string | ISceneLoaderPluginExtensions;
-        importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void) => boolean;
-        load: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void) => boolean;
+
+        /**
+         * Import meshes into a scene.
+         * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
+         * @param scene The scene to import into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param meshes The meshes array to import into
+         * @param particleSystems The particle systems array to import into
+         * @param skeletons The skeletons array to import into
+         * @param onError The callback when import fails
+         * @returns True if successful or false otherwise
+         */
+        importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean;
+
+        /**
+         * Load into a scene.
+         * @param scene The scene to load into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param onError The callback when import fails
+         * @returns true if successful or false otherwise
+         */
+        load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean;
+
+        /**
+         * The callback that returns true if the data can be directly loaded.
+         */
         canDirectLoad?: (data: string) => boolean;
+
+        /**
+         * The callback that allows custom handling of the root url based on the response url.
+         */
         rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
-        loadAssets: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void) => Nullable<AssetContainer>;
+
+        /**
+         * Load into an asset container.
+         * @param scene The scene to load into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param onError The callback when import fails
+         * @returns The loaded asset container
+         */
+        loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
     }
 
     export interface ISceneLoaderPluginAsync {
+        /**
+         * The friendly name of this plugin.
+         */
         name: string;
+
+        /**
+         * The file extensions supported by this plugin.
+         */
         extensions: string | ISceneLoaderPluginExtensions;
-        importMeshAsync: (meshesNames: any, scene: Scene, data: any, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
-        loadAsync: (scene: Scene, data: string, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+
+        /**
+         * Import meshes into a scene.
+         * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
+         * @param scene The scene to import into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param onProgress The callback when the load progresses
+         * @returns The loaded meshes, particle systems, and skeletons
+         */
+        importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }>;
+
+        /**
+         * Load into a scene.
+         * @param scene The scene to load into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param onProgress The callback when the load progresses
+         * @returns Nothing
+         */
+        loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
+
+        /**
+         * The callback that returns true if the data can be directly loaded.
+         */
         canDirectLoad?: (data: string) => boolean;
+
+        /**
+         * The callback that allows custom handling of the root url based on the response url.
+         */
         rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
-        loadAssetsAsync: (scene: Scene, data: string, rootUrl: string, onSuccess?: (assets: Nullable<AssetContainer>) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void) => void;
+
+        /**
+         * Load into an asset container.
+         * @param scene The scene to load into
+         * @param data The data to import
+         * @param rootUrl The root url for scene and resources
+         * @param onProgress The callback when the load progresses
+         * @returns The loaded asset container
+         */
+        loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
     }
 
     interface IRegisteredPlugin {
@@ -209,7 +298,7 @@
                 let url = rootUrl + sceneFilename;
                 request = Tools.LoadFile(url, dataCallback, onProgress ? event => {
                     onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
-                }: undefined, database, useArrayBuffer, (request, exception) => {
+                } : undefined, database, useArrayBuffer, (request, exception) => {
                     onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
                 });
             };
@@ -272,15 +361,17 @@
         }
 
         /**
-        * Import meshes into a scene
-        * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported 
-        * @param rootUrl a string that defines the root url for scene and resources
-        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
-        * @param scene the instance of BABYLON.Scene to append to
-        * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
-        * @param onProgress a callback with a progress event for each file being loaded
-        * @param onError a callback with the scene, a message, and possibly an exception when import fails
-        */
+         * Import meshes into a scene
+         * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported 
+         * @param rootUrl a string that defines the root url for scene and resources
+         * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+         * @param scene the instance of BABYLON.Scene to append to
+         * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
+         * @param onProgress a callback with a progress event for each file being loaded
+         * @param onError a callback with the scene, a message, and possibly an exception when import fails
+         * @param pluginExtension the extension used to determine the plugin
+         * @returns The loaded plugin
+         */
         public static ImportMesh(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onSuccess: Nullable<(meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
             if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
                 Tools.Error("Wrong sceneFilename parameter");
@@ -357,15 +448,41 @@
                 }
                 else {
                     var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
-                    asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, (meshes, particleSystems, skeletons) => {
+                    asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(result => {
                         scene.loadingPluginName = plugin.name;
-                        successHandler(meshes, particleSystems, skeletons);
-                    }, progressHandler, errorHandler);
+                        successHandler(result.meshes, result.particleSystems, result.skeletons);
+                    }).catch(error => {
+                        errorHandler(error.message, error);
+                    });
                 }
             }, progressHandler, errorHandler, disposeHandler, pluginExtension);
         }
 
         /**
+        * Import meshes into a scene
+        * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported 
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene the instance of BABYLON.Scene to append to
+        * @param onProgress a callback with a progress event for each file being loaded
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded list of imported meshes, particleSystems, and skeletons
+        */
+        public static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }> {
+            return new Promise((resolve, reject) => {
+                SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons) => {
+                    resolve({
+                        meshes: meshes,
+                        particleSystems: particleSystems,
+                        skeletons: skeletons
+                    });
+                }, onProgress, (scene, message, exception) => {
+                    reject(exception || new Error(message));
+                });
+            });
+        }
+
+        /**
         * Load a scene
         * @param rootUrl a string that defines the root url for scene and resources
         * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
@@ -373,12 +490,33 @@
         * @param onSuccess a callback with the scene when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded plugin
         */
         public static Load(rootUrl: string, sceneFilename: any, engine: Engine, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
             return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension);
         }
 
         /**
+        * Load a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param engine is the instance of BABYLON.Engine to use to create the scene
+        * @param onProgress a callback with a progress event for each file being loaded
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded scene
+        */
+        public static LoadAsync(rootUrl: string, sceneFilename: any, engine: Engine, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
+            return new Promise((resolve, reject) => {
+                SceneLoader.Load(rootUrl, sceneFilename, engine, scene => {
+                    resolve(scene);
+                }, onProgress, (scene, message, exception) => {
+                    reject(exception || new Error(message));
+                }, pluginExtension);
+            });
+        }
+
+        /**
         * Append a scene
         * @param rootUrl a string that defines the root url for scene and resources
         * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
@@ -386,6 +524,8 @@
         * @param onSuccess a callback with the scene when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded plugin
         */
         public static Append(rootUrl: string, sceneFilename: any, scene: Scene, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
             if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
@@ -454,10 +594,12 @@
                     successHandler();
                 } else {
                     var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
-                    asyncedPlugin.loadAsync(scene, data, rootUrl, () => {
+                    asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(() => {
                         scene.loadingPluginName = plugin.name;
                         successHandler();
-                    }, progressHandler, errorHandler);
+                    }).catch(error => {
+                        errorHandler(error.message, error);
+                    });
                 }
 
                 if (SceneLoader.ShowLoadingScreen) {
@@ -467,7 +609,37 @@
                 }
             }, progressHandler, errorHandler, disposeHandler, pluginExtension);
         }
-        
+
+        /**
+        * Append a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene is the instance of BABYLON.Scene to append to
+        * @param onProgress a callback with a progress event for each file being loaded
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The given scene
+        */
+        public static AppendAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
+            return new Promise((resolve, reject) => {
+                SceneLoader.Append(rootUrl, sceneFilename, scene, scene => {
+                    resolve(scene);
+                }, onProgress, (scene, message, exception) => {
+                    reject(exception || new Error(message));
+                }, pluginExtension);
+            });
+        }
+
+        /**
+        * Load a scene into an asset container
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene is the instance of BABYLON.Scene to append to
+        * @param onSuccess a callback with the scene when import succeeds
+        * @param onProgress a callback with a progress event for each file being loaded
+        * @param onError a callback with the scene, a message, and possibly an exception when import fails
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded plugin
+        */
         public static LoadAssetContainer(
             rootUrl: string,
             sceneFilename: any,
@@ -524,25 +696,25 @@
             };
 
             return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
-                if ((<any>plugin).loadAssets) {
+                if ((<any>plugin).loadAssetContainer) {
                     var syncedPlugin = <ISceneLoaderPlugin>plugin;
-                    var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
+                    var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
                     if (!assetContainer) {
                         return;
                     }
 
                     scene.loadingPluginName = plugin.name;
                     successHandler(assetContainer);
-                } else if ((<any>plugin).loadAssetsAsync) {
+                } else if ((<any>plugin).loadAssetContainerAsync) {
                     var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
-                    asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, (assetContainer) => {
-                        if(assetContainer){
-                            scene.loadingPluginName = plugin.name;
-                            successHandler(assetContainer);
-                        }
-                    }, progressHandler, errorHandler);
-                }else{
-                    errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.")
+                    asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(assetContainer => {
+                        scene.loadingPluginName = plugin.name;
+                        successHandler(assetContainer);
+                    }).catch(error => {
+                        errorHandler(error.message, error);
+                    });
+                } else {
+                    errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")
                 }
 
                 if (SceneLoader.ShowLoadingScreen) {
@@ -552,5 +724,24 @@
                 }
             }, progressHandler, errorHandler, disposeHandler, pluginExtension);
         }
+
+        /**
+        * Load a scene into an asset container
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene is the instance of BABYLON.Scene to append to
+        * @param onProgress a callback with a progress event for each file being loaded
+        * @param pluginExtension the extension used to determine the plugin
+        * @returns The loaded asset container
+        */
+        public static LoadAssetContainerAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<AssetContainer> {
+            return new Promise((resolve, reject) => {
+                SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, assetContainer => {
+                    resolve(assetContainer);
+                }, onProgress, (scene, message, exception) => {
+                    reject(exception || new Error(message));
+                }, pluginExtension);
+            });
+        }
     };
 }

+ 29 - 2
src/Materials/Background/babylon.backgroundMaterial.ts

@@ -95,6 +95,7 @@
         public REFLECTIONMAP_OPPOSITEZ = false;
         public LODINREFLECTIONALPHA = false;
         public GAMMAREFLECTION = false;
+        public EQUIRECTANGULAR_RELFECTION_FOV = false;
 
         // Default BJS.
         public MAINUV1 = false;
@@ -330,6 +331,28 @@
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public enableNoise: boolean = false;
 
+        /**
+         * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
+         * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
+         * Recommended to be keep at 1.0 except for special cases.
+         */
+        public get fovMultiplier(): number {
+            return this._fovMultiplier;
+        }
+        public set fovMultiplier(value: number) {
+            if (isNaN(value)) {
+                value = 1.0;
+            }
+            this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
+        }
+        private _fovMultiplier: float = 1.0;
+
+        /**
+         * Enable the FOV adjustment feature controlled by fovMultiplier.
+         * @type {boolean}
+         */
+        public useEquirectangularFOV: boolean = false;
+
         @serialize()
         private _maxSimultaneousLights: int = 4;
         /**
@@ -611,6 +634,7 @@
                         defines.REFLECTIONBLUR = this._reflectionBlur > 0;
                         defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
                         defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
+                        defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
 
                         if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {
                             defines.INVERTCUBICMAP = true;
@@ -756,7 +780,7 @@
                     "vClipPlane", "mBones",
 
                     "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
-                    "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
+                    "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
 
                     "shadowLevel", "alpha",
 
@@ -826,6 +850,7 @@
             this._uniformBuffer.addUniform("diffuseMatrix", 16);
             this._uniformBuffer.addUniform("reflectionMatrix", 16);
             this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
+            this._uniformBuffer.addUniform("fFovMultiplier", 1);
             this._uniformBuffer.addUniform("pointSize", 1);
             this._uniformBuffer.addUniform("shadowLevel", 1);
             this._uniformBuffer.addUniform("alpha", 1);
@@ -925,6 +950,8 @@
                     this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
                 }
 
+                this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
+
                 // Textures
                 if (scene.texturesEnabled) {
                     if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
@@ -1039,4 +1066,4 @@
             return SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl);
         }
     }
-}
+}

File diff suppressed because it is too large
+ 425 - 271
src/Materials/PBR/babylon.pbrBaseMaterial.ts


+ 67 - 0
src/Materials/PBR/babylon.pbrMaterial.ts

@@ -15,7 +15,11 @@
             return this._PBRMATERIAL_OPAQUE;
         }
 
+        /**
+         * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
+         */
         private static _PBRMATERIAL_ALPHATEST = 1;
+
         /**
          * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
          */
@@ -23,7 +27,11 @@
             return this._PBRMATERIAL_ALPHATEST;
         }
 
+        /**
+         * Represents the value for Alpha Blend.  Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+         */
         private static _PBRMATERIAL_ALPHABLEND = 2;
+
         /**
          * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
          */
@@ -31,7 +39,12 @@
             return this._PBRMATERIAL_ALPHABLEND;
         }
 
+        /**
+         * Represents the value for Alpha Test and Blend.  Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+         * They are also discarded below the alpha cutoff threshold to improve performances.
+         */
         private static _PBRMATERIAL_ALPHATESTANDBLEND = 3;
+
         /**
          * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
          * They are also discarded below the alpha cutoff threshold to improve performances.
@@ -100,14 +113,23 @@
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public ambientTextureStrength: number = 1.0;
 
+        /**
+         * Stores the alpha values in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
         public opacityTexture: BaseTexture;
 
+        /**
+         * Stores the reflection values in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public reflectionTexture: Nullable<BaseTexture>;
 
+        /**
+         * Stores the emissive values in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public emissiveTexture: BaseTexture;
@@ -150,18 +172,30 @@
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public microSurfaceTexture: BaseTexture;
 
+        /**
+         * Stores surface normal data used to displace a mesh in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public bumpTexture: BaseTexture;
 
+        /**
+         * Stores the pre-calculated light information of a mesh in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
         public lightmapTexture: BaseTexture;
 
+        /**
+         * Stores the refracted light information in a texture.
+         */
         @serializeAsTexture()
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public refractionTexture: BaseTexture;
 
+        /**
+         * The color of a material in ambient lighting.
+         */
         @serializeAsColor3("ambient")
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public ambientColor = new Color3(0, 0, 0);
@@ -180,10 +214,16 @@
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public reflectivityColor = new Color3(1, 1, 1);
 
+        /**
+         * The color reflected from the material.
+         */
         @serializeAsColor3("reflection")
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public reflectionColor = new Color3(1.0, 1.0, 1.0);
 
+        /**
+         * The color emitted from the material.
+         */
         @serializeAsColor3("emissive")
         @expandToProperty("_markAllSubMeshesAsTexturesDirty")
         public emissiveColor = new Color3(0, 0, 0);
@@ -560,10 +600,17 @@
             this._environmentBRDFTexture = TextureTools.GetEnvironmentBRDFTexture(scene);
         }
 
+        /**
+         * Returns the name of this material class.
+         */
         public getClassName(): string {
             return "PBRMaterial";
         }
 
+        /**
+         * Returns an array of the actively used textures.
+         * @returns - Array of BaseTextures
+         */
         public getActiveTextures(): BaseTexture[] {
             var activeTextures = super.getActiveTextures();
 
@@ -614,6 +661,11 @@
             return activeTextures;
         }
 
+        /**
+         * Checks to see if a texture is used in the material.
+         * @param texture - Base texture to use.
+         * @returns - Boolean specifying if a texture is used in the material.
+         */
         public hasTexture(texture: BaseTexture): boolean {
             if (super.hasTexture(texture)) {
                 return true;
@@ -662,6 +714,10 @@
             return false;
         }
 
+        /**
+         * Makes a duplicate of the current material.
+         * @param name - name to use for the new material.
+         */
         public clone(name: string): PBRMaterial {
             var clone = SerializationHelper.Clone(() => new PBRMaterial(name, this.getScene()), this);
 
@@ -671,6 +727,10 @@
             return clone;
         }
 
+        /**
+         * Serializes this PBR Material.
+         * @returns - An object with the serialized material.
+         */
         public serialize(): any {
             var serializationObject = SerializationHelper.Serialize(this);
             serializationObject.customType = "BABYLON.PBRMaterial";
@@ -678,6 +738,13 @@
         }
 
         // Statics
+        /**
+         * Parses a PBR Material from a serialized object.
+         * @param source - Serialized object.
+         * @param scene - BJS scene instance.
+         * @param rootUrl - url for the scene object
+         * @returns - PBRMaterial
+         */
         public static Parse(source: any, scene: Scene, rootUrl: string): PBRMaterial {
             return SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl);
         }

+ 9 - 0
src/Materials/PBR/babylon.pbrMetallicRoughnessMaterial.ts

@@ -87,6 +87,11 @@
             return activeTextures;
         }
 
+        /**
+         * Checks to see if a texture is used in the material.
+         * @param texture - Base texture to use.
+         * @returns - Boolean specifying if a texture is used in the material.
+         */
         public hasTexture(texture: BaseTexture): boolean {
             if (super.hasTexture(texture)) {
                 return true;
@@ -103,6 +108,10 @@
             return false;
         }
 
+        /**
+         * Makes a duplicate of the current material.
+         * @param name - name to use for the new material.
+         */
         public clone(name: string): PBRMetallicRoughnessMaterial {
             var clone = SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name, this.getScene()), this);
 

+ 9 - 0
src/Materials/PBR/babylon.pbrSpecularGlossinessMaterial.ts

@@ -78,6 +78,11 @@
             return activeTextures;
         }
 
+        /**
+         * Checks to see if a texture is used in the material.
+         * @param texture - Base texture to use.
+         * @returns - Boolean specifying if a texture is used in the material.
+         */
         public hasTexture(texture: BaseTexture): boolean {
             if (super.hasTexture(texture)) {
                 return true;
@@ -94,6 +99,10 @@
             return false;
         }
 
+        /**
+         * Makes a duplicate of the current material.
+         * @param name - name to use for the new material.
+         */
         public clone(name: string): PBRSpecularGlossinessMaterial {
             var clone = SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name, this.getScene()), this);
 

+ 26 - 1
src/Materials/Textures/babylon.baseTexture.ts

@@ -43,9 +43,34 @@
         public get coordinatesMode(): number {
             return this._coordinatesMode;
         }
+        
+        /*
+        * How a texture is mapped.
+        *
+        * | Value | Type                                | Description |
+        * | ----- | ----------------------------------- | ----------- |
+        * | 0     | EXPLICIT_MODE                       |             |
+        * | 1     | SPHERICAL_MODE                      |             |
+        * | 2     | PLANAR_MODE                         |             |
+        * | 3     | CUBIC_MODE                          |             |
+        * | 4     | PROJECTION_MODE                     |             |
+        * | 5     | SKYBOX_MODE                         |             |
+        * | 6     | INVCUBIC_MODE                       |             |
+        * | 7     | EQUIRECTANGULAR_MODE                |             |
+        * | 8     | FIXED_EQUIRECTANGULAR_MODE          |             |
+        * | 9     | FIXED_EQUIRECTANGULAR_MIRRORED_MODE |             |
+        */
 
         @serialize()
         public wrapU = Texture.WRAP_ADDRESSMODE;
+        
+        /* 
+        * | Value | Type               | Description |
+        * | ----- | ------------------ | ----------- |
+        * | 0     | CLAMP_ADDRESSMODE  |             |
+        * | 1     | WRAP_ADDRESSMODE   |             |
+        * | 2     | MIRROR_ADDRESSMODE |             |
+        */
 
         @serialize()
         public wrapV = Texture.WRAP_ADDRESSMODE;
@@ -378,4 +403,4 @@
             }
         }
     }
-} 
+} 

+ 28 - 0
src/Materials/Textures/babylon.cubeTexture.ts

@@ -3,6 +3,34 @@
         public url: string;
         public coordinatesMode = Texture.CUBIC_MODE;
 
+        /**
+         * Gets or sets the center of the bounding box associated with the cube texture
+         * It must define where the camera used to render the texture was set
+         */
+        public boundingBoxPosition = Vector3.Zero();
+
+        private _boundingBoxSize: Vector3;
+
+        /**
+         * Gets or sets the size of the bounding box associated with the cube texture
+         * When defined, the cubemap will switch to local mode
+         * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
+         * @example https://www.babylonjs-playground.com/#RNASML
+         */
+        public set boundingBoxSize(value: Vector3) {
+            if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
+                return;
+            }
+            this._boundingBoxSize = value;
+            let scene = this.getScene();
+            if (scene) {
+                scene.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
+            }
+        }
+        public get boundingBoxSize(): Vector3 {
+            return this._boundingBoxSize;
+        }
+
         private _noMipmap: boolean;
         private _files: string[];
         private _extensions: string[];

+ 28 - 0
src/Materials/Textures/babylon.renderTargetTexture.ts

@@ -128,6 +128,34 @@
             }
         }
 
+        /**
+         * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
+         * It must define where the camera used to render the texture is set
+         */
+        public boundingBoxPosition = Vector3.Zero();
+
+        private _boundingBoxSize: Vector3;
+
+        /**
+         * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
+         * When defined, the cubemap will switch to local mode
+         * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
+         * @example https://www.babylonjs-playground.com/#RNASML
+         */        
+        public set boundingBoxSize(value: Vector3) {
+            if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
+                return;
+            }
+            this._boundingBoxSize = value;
+            let scene = this.getScene();
+            if (scene) {
+                scene.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
+            }
+        }
+        public get boundingBoxSize(): Vector3 {
+            return this._boundingBoxSize;
+        }
+
         constructor(name: string, size: number | {width: number, height: number} | {ratio: number}, scene: Nullable<Scene>, generateMipMaps?: boolean, doNotChangeAspectRatio: boolean = true, type: number = Engine.TEXTURETYPE_UNSIGNED_INT, public isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false) {
             super(null, scene, !generateMipMaps);
             scene = this.getScene();

+ 4 - 1
src/Materials/Textures/babylon.videoTexture.ts

@@ -92,18 +92,21 @@
             if (typeof src === "object") {
                 return src.toString();
             }
-    
+
             return src;
         };
     
         private _getVideo(src: string | string[] | HTMLVideoElement): HTMLVideoElement {
             if (src instanceof HTMLVideoElement) {
+                Tools.SetCorsBehavior(src.currentSrc, src);
                 return src;
             }
             const video: HTMLVideoElement = document.createElement("video");
             if (typeof src === "string") {
+                Tools.SetCorsBehavior(src, video);
                 video.src = src;
             } else {
+                Tools.SetCorsBehavior(src[0], video);
                 src.forEach(url => {
                     const source = document.createElement("source");
                     source.src = url;

File diff suppressed because it is too large
+ 490 - 8
src/Materials/babylon.material.ts


+ 8 - 3
src/Materials/babylon.materialHelper.ts

@@ -84,12 +84,17 @@ module BABYLON {
          * @param engine defines the current engine
          * @param defines specifies the list of active defines
          * @param useInstances defines if instances have to be turned on
+         * @param useClipPlane defines if clip plane have to be turned on
          */
-        public static PrepareDefinesForFrameBoundValues(scene: Scene, engine: Engine, defines: any, useInstances: boolean): void {
+        public static PrepareDefinesForFrameBoundValues(scene: Scene, engine: Engine, defines: any, useInstances: boolean, useClipPlane: Nullable<boolean> = null): void {
             var changed = false;
 
-            if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
-                defines["CLIPPLANE"] = !defines["CLIPPLANE"];
+            if (useClipPlane == null) {
+                useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
+            }
+
+            if (defines["CLIPPLANE"] !== useClipPlane) {
+                defines["CLIPPLANE"] = useClipPlane;
                 changed = true;
             }
 

+ 14 - 0
src/Materials/babylon.standardMaterial.ts

@@ -1,4 +1,5 @@
 module BABYLON {
+    /** @ignore */
     export class StandardMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
         public MAINUV1 = false;
         public MAINUV2 = false;
@@ -52,6 +53,7 @@ module BABYLON {
         public REFLECTIONMAP_SPHERICAL = false;
         public REFLECTIONMAP_PLANAR = false;
         public REFLECTIONMAP_CUBIC = false;
+        public USE_LOCAL_REFLECTIONMAP_CUBIC = false;
         public REFLECTIONMAP_PROJECTION = false;
         public REFLECTIONMAP_SKYBOX = false;
         public REFLECTIONMAP_EXPLICIT = false;
@@ -616,6 +618,8 @@ module BABYLON {
                                     defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
                                     break;
                             }
+
+                            defines.USE_LOCAL_REFLECTIONMAP_CUBIC = (<any>this._reflectionTexture).boundingBoxSize ? true : false;
                         }
                     } else {
                         defines.REFLECTION = false;
@@ -847,6 +851,7 @@ module BABYLON {
                     "mBones",
                     "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
                     "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
+                    "vReflectionPosition", "vReflectionSize",
                     "logarithmicDepthConstant", "vTangentSpaceParams"
                 ];
 
@@ -911,6 +916,8 @@ module BABYLON {
             this._uniformBuffer.addUniform("vAmbientInfos", 2);
             this._uniformBuffer.addUniform("vOpacityInfos", 2);
             this._uniformBuffer.addUniform("vReflectionInfos", 2);
+            this._uniformBuffer.addUniform("vReflectionPosition", 3);
+            this._uniformBuffer.addUniform("vReflectionSize", 3);
             this._uniformBuffer.addUniform("vEmissiveInfos", 2);
             this._uniformBuffer.addUniform("vLightmapInfos", 2);
             this._uniformBuffer.addUniform("vSpecularInfos", 2);
@@ -1024,6 +1031,13 @@ module BABYLON {
                         if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                             this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
                             this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
+
+                            if ((<any>this._reflectionTexture).boundingBoxSize) {
+                                let cubeTexture = <CubeTexture>this._reflectionTexture;
+
+                                this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
+                                this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
+                            }
                         }
 
                         if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {

File diff suppressed because it is too large
+ 373 - 116
src/Math/babylon.math.ts


+ 2 - 2
src/Mesh/babylon.mesh.ts

@@ -3310,8 +3310,8 @@
                     minVector = boundingBox.minimumWorld;
                     maxVector = boundingBox.maximumWorld;
                 } else {
-                    minVector.MinimizeInPlace(boundingBox.minimumWorld);
-                    maxVector.MaximizeInPlace(boundingBox.maximumWorld);
+                    minVector.minimizeInPlace(boundingBox.minimumWorld);
+                    maxVector.maximizeInPlace(boundingBox.maximumWorld);
                 }
             });
 

+ 75 - 38
src/Mesh/babylon.mesh.vertexData.ts

@@ -291,8 +291,26 @@
          * Merges the passed VertexData into the current one.  
          * Returns the modified VertexData.  
          */
-        public merge(other: VertexData, options?: { tangentLength?: number }): VertexData {
-            options = options || {};
+        public merge(other: VertexData): VertexData {
+            this._validate();
+            other._validate();
+
+            if (!this.normals !== !other.normals ||
+                !this.tangents !== !other.tangents ||
+                !this.uvs !== !other.uvs ||
+                !this.uvs2 !== !other.uvs2 ||
+                !this.uvs3 !== !other.uvs3 ||
+                !this.uvs4 !== !other.uvs4 ||
+                !this.uvs5 !== !other.uvs5 ||
+                !this.uvs6 !== !other.uvs6 ||
+                !this.colors !== !other.colors ||
+                !this.matricesIndices !== !other.matricesIndices ||
+                !this.matricesWeights !== !other.matricesWeights ||
+                !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
+                !this.matricesWeightsExtra !== !other.matricesWeightsExtra)
+            {
+                throw new Error("Cannot merge vertex data that do not have the same set of attributes");
+            }
 
             if (other.indices) {
                 if (!this.indices) {
@@ -307,48 +325,29 @@
             }
 
             this.positions = this._mergeElement(this.positions, other.positions);
-
-            if (!this.positions) {
-                return this;
-            }
-
-            var count = this.positions.length / 3;
-
-            this.normals = this._mergeElement(this.normals, other.normals, count * 3);
-            this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
-            this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
-            this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
-            this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
-            this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
-            this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
-            this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
-            this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
-            this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
-            this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
-            this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
-            this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
+            this.normals = this._mergeElement(this.normals, other.normals);
+            this.tangents = this._mergeElement(this.tangents, other.tangents);
+            this.uvs = this._mergeElement(this.uvs, other.uvs);
+            this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
+            this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
+            this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
+            this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
+            this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
+            this.colors = this._mergeElement(this.colors, other.colors);
+            this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
+            this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
+            this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
+            this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
             return this;
         }
 
-        private _mergeElement(source: Nullable<FloatArray>, other: Nullable<FloatArray>, length = 0, defaultValue = 0): Nullable<FloatArray> {
-            if (!other && !source) {
-                return null;
+        private _mergeElement(source: Nullable<FloatArray>, other: Nullable<FloatArray>): Nullable<FloatArray> {
+            if (!source) {
+                return other;
             }
 
             if (!other) {
-                var padding = new Float32Array((<FloatArray>source).length);
-                padding.fill(defaultValue);
-                return this._mergeElement(source, padding, length);
-            }
-
-            if (!source) {
-                if (length === 0 || length === other.length) {
-                    return other;
-                }
-
-                var padding = new Float32Array(length - other.length);
-                padding.fill(defaultValue);
-                return this._mergeElement(padding, other, length);
+                return source;
             }
 
             var len = other.length + source.length;
@@ -376,6 +375,44 @@
             }
         }
 
+        private _validate(): void {
+            if (!this.positions) {
+                throw new Error("Positions are required");
+            }
+
+            const getElementCount = (kind: string, values: FloatArray) => {
+                const stride = VertexBuffer.DeduceStride(kind);
+                if ((values.length % stride) !== 0) {
+                    throw new Error("The " + kind + "s array count must be a multiple of " + stride);
+                }
+
+                return values.length / stride;
+            };
+
+            const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions);
+
+            const validateElementCount = (kind: string, values: FloatArray) => {
+                const elementCount = getElementCount(kind, values);
+                if (elementCount !== positionsElementCount) {
+                    throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
+                }
+            };
+
+            if (this.normals) validateElementCount(VertexBuffer.NormalKind, this.normals);
+            if (this.tangents) validateElementCount(VertexBuffer.TangentKind, this.tangents);
+            if (this.uvs) validateElementCount(VertexBuffer.UVKind, this.uvs);
+            if (this.uvs2) validateElementCount(VertexBuffer.UV2Kind, this.uvs2);
+            if (this.uvs3) validateElementCount(VertexBuffer.UV3Kind, this.uvs3);
+            if (this.uvs4) validateElementCount(VertexBuffer.UV4Kind, this.uvs4);
+            if (this.uvs5) validateElementCount(VertexBuffer.UV5Kind, this.uvs5);
+            if (this.uvs6) validateElementCount(VertexBuffer.UV6Kind, this.uvs6);
+            if (this.colors) validateElementCount(VertexBuffer.ColorKind, this.colors);
+            if (this.matricesIndices) validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices);
+            if (this.matricesWeights) validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights);
+            if (this.matricesIndicesExtra) validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
+            if (this.matricesWeightsExtra) validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
+        }
+
         /**
          * Serializes the VertexData.  
          * Returns a serialized object.  

+ 1 - 1
src/Mesh/babylon.transformNode.ts

@@ -425,7 +425,7 @@ module BABYLON {
                 point = Vector3.TransformCoordinates(point, tmat);
             }
 
-            return this.setPivotMatrix(Matrix.Translation(point.x, point.y, point.z), true);
+            return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);
         }
 
         /**

+ 33 - 30
src/Mesh/babylon.vertexBuffer.ts

@@ -9,36 +9,7 @@
 
         constructor(engine: any, data: FloatArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number, instanced?: boolean, offset?: number, size?: number) {
             if (!stride) {
-                // Deduce stride from kind
-                switch (kind) {
-                    case VertexBuffer.PositionKind:
-                        stride = 3;
-                        break;
-                    case VertexBuffer.NormalKind:
-                        stride = 3;
-                        break;
-                    case VertexBuffer.UVKind:
-                    case VertexBuffer.UV2Kind:
-                    case VertexBuffer.UV3Kind:
-                    case VertexBuffer.UV4Kind:
-                    case VertexBuffer.UV5Kind:
-                    case VertexBuffer.UV6Kind:
-                        stride = 2;
-                        break;
-                    case VertexBuffer.TangentKind:
-                    case VertexBuffer.ColorKind:
-                        stride = 4;
-                        break;
-                    case VertexBuffer.MatricesIndicesKind:
-                    case VertexBuffer.MatricesIndicesExtraKind:
-                        stride = 4;
-                        break;
-                    case VertexBuffer.MatricesWeightsKind:
-                    case VertexBuffer.MatricesWeightsExtraKind:
-                    default:
-                        stride = 4;
-                        break;
-                }
+                stride = VertexBuffer.DeduceStride(kind);
             }
 
             if (data instanceof Buffer) {
@@ -240,5 +211,37 @@
         public static get MatricesWeightsExtraKind(): string {
             return VertexBuffer._MatricesWeightsExtraKind;
         }
+
+        /**
+         * Deduces the stride given a kind.
+         * @param kind The kind string to deduce
+         * @returns The deduced stride
+         */
+        public static DeduceStride(kind: string): number {
+            switch (kind) {
+                case VertexBuffer.PositionKind:
+                    return 3;
+                case VertexBuffer.NormalKind:
+                    return 3;
+                case VertexBuffer.UVKind:
+                case VertexBuffer.UV2Kind:
+                case VertexBuffer.UV3Kind:
+                case VertexBuffer.UV4Kind:
+                case VertexBuffer.UV5Kind:
+                case VertexBuffer.UV6Kind:
+                    return 2;
+                case VertexBuffer.TangentKind:
+                case VertexBuffer.ColorKind:
+                    return 4;
+                case VertexBuffer.MatricesIndicesKind:
+                case VertexBuffer.MatricesIndicesExtraKind:
+                    return 4;
+                case VertexBuffer.MatricesWeightsKind:
+                case VertexBuffer.MatricesWeightsExtraKind:
+                    return 4;
+                default:
+                    throw new Error("Invalid kind '" + kind + "'");
+            }
+        }
     }
 } 

+ 6 - 0
src/Particles/babylon.solidParticle.ts

@@ -41,6 +41,12 @@ module BABYLON {
          */
         public pivot: Vector3 = Vector3.Zero();
         /**
+         * Must the particle be translated from its pivot point in its local space ?
+         * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.  
+         * Default : false
+         */
+        public translateFromPivot: boolean = false;
+        /**
          * Is the particle active or not ?
          */
         public alive: boolean = true;

+ 47 - 14
src/Particles/babylon.solidParticleSystem.ts

@@ -123,16 +123,17 @@
             private _sinYaw: number = 0.0;
             private _cosYaw: number = 0.0;
             private _mustUnrotateFixedNormals = false;
-            private _minimum: Vector3 = Tmp.Vector3[0];
-            private _maximum: Vector3 = Tmp.Vector3[1];
-            private _minBbox: Vector3 = Tmp.Vector3[4];
-            private _maxBbox: Vector3 = Tmp.Vector3[5];
+            private _minimum: Vector3 = Vector3.Zero();
+            private _maximum: Vector3 = Vector3.Zero();
+            private _minBbox: Vector3 = Vector3.Zero();
+            private _maxBbox: Vector3 = Vector3.Zero();
             private _particlesIntersect: boolean = false;
             private _depthSortFunction: (p1: DepthSortedParticle, p2: DepthSortedParticle) => number = 
                 function(p1, p2) {
                     return (p2.sqDistance - p1.sqDistance);
                 };
             private _needs32Bits: boolean = false;
+            private _pivotBackTranslation: Vector3 = Vector3.Zero();
 
             /**
              * Creates a SPS (Solid Particle System) object.
@@ -258,7 +259,7 @@
                 var facetInd: number[] = [];      // submesh indices
                 var facetUV: number[] = [];       // submesh UV
                 var facetCol: number[] = [];      // submesh colors
-                var barycenter: Vector3 = Tmp.Vector3[0];
+                var barycenter: Vector3 = Vector3.Zero();
                 var sizeO: number = size;
     
                 while (f < totalFacets) {
@@ -373,6 +374,7 @@
                 this._copy.uvs.z = 1.0;
                 this._copy.uvs.w = 1.0;
                 this._copy.color = null;
+                this._copy.translateFromPivot = false;
             }
     
             // _meshBuilder : inserts the shape model in the global SPS mesh
@@ -397,6 +399,13 @@
                     this._quaternionRotationYPR();
                 }
                 this._quaternionToRotationMatrix();
+                
+                if (this._copy.translateFromPivot) {
+                    this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
+                }
+                else {
+                    this._pivotBackTranslation.copyFrom(this._copy.pivot);
+                }
     
                 for (i = 0; i < shape.length; i++) {
                     this._vertex.x = shape[i].x;
@@ -411,11 +420,13 @@
                     this._vertex.y *= this._copy.scaling.y;
                     this._vertex.z *= this._copy.scaling.z;
 
-                    this._vertex.x += this._copy.pivot.x;
-                    this._vertex.y += this._copy.pivot.y;
-                    this._vertex.z += this._copy.pivot.z;
+                    this._vertex.x -= this._copy.pivot.x;
+                    this._vertex.y -= this._copy.pivot.y;
+                    this._vertex.z -= this._copy.pivot.z;
     
                     Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
+
+                    this._rotated.addInPlace(this._pivotBackTranslation);
                     positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
                     if (meshUV) {
                         uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
@@ -570,6 +581,13 @@
                     this._quaternionRotationYPR();
                 }
                 this._quaternionToRotationMatrix();
+
+                if (this._copy.translateFromPivot) {
+                    this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
+                }
+                else {
+                    this._pivotBackTranslation.copyFrom(this._copy.pivot);
+                }
     
                 this._shape = particle._model._shape;
                 for (var pt = 0; pt < this._shape.length; pt++) {
@@ -585,11 +603,12 @@
                     this._vertex.y *= this._copy.scaling.y;
                     this._vertex.z *= this._copy.scaling.z;
 
-                    this._vertex.x += this._copy.pivot.x;
-                    this._vertex.y += this._copy.pivot.y;
-                    this._vertex.z += this._copy.pivot.z;
+                    this._vertex.x -= this._copy.pivot.x;
+                    this._vertex.y -= this._copy.pivot.y;
+                    this._vertex.z -= this._copy.pivot.z;
     
                     Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
+                    this._rotated.addInPlace(this._pivotBackTranslation);
     
                     this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
                     this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
@@ -759,6 +778,16 @@
                             this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
                         }
        
+                        if (this._particle.translateFromPivot) {
+                            this._pivotBackTranslation.x = 0.0;
+                            this._pivotBackTranslation.y = 0.0;
+                            this._pivotBackTranslation.z = 0.0;
+                        }
+                        else {
+                            this._pivotBackTranslation.x = this._particle.pivot.x;
+                            this._pivotBackTranslation.y = this._particle.pivot.y;
+                            this._pivotBackTranslation.z = this._particle.pivot.z;
+                        }
                         // particle vertex loop
                         for (pt = 0; pt < this._shape.length; pt++) {
                             idx = index + pt * 3;
@@ -778,14 +807,18 @@
                             this._vertex.y *= this._particle.scaling.y;
                             this._vertex.z *= this._particle.scaling.z;
 
-                            this._vertex.x += this._particle.pivot.x;
-                            this._vertex.y += this._particle.pivot.y;
-                            this._vertex.z += this._particle.pivot.z;
+                            this._vertex.x -= this._particle.pivot.x;
+                            this._vertex.y -= this._particle.pivot.y;
+                            this._vertex.z -= this._particle.pivot.z;
     
                             this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
                             this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
                             this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
     
+                            this._rotated.x += this._pivotBackTranslation.x;
+                            this._rotated.y += this._pivotBackTranslation.y;
+                            this._rotated.z += this._pivotBackTranslation.z;
+
                             this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                             this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                             this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;

+ 2 - 2
src/Rendering/babylon.renderingGroup.ts

@@ -362,8 +362,8 @@
             // Particles
             var activeCamera = this._scene.activeCamera;
             this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
-            for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
-                var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
+            for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
+                var particleSystem = this._particleSystems.data[particleIndex];
 
                 if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
                     continue;

+ 1 - 0
src/Shaders/ShadersInclude/backgroundUboDeclaration.fx

@@ -10,6 +10,7 @@ uniform Material
 	uniform mat4 diffuseMatrix;
 	uniform mat4 reflectionMatrix;
 	uniform vec3 vReflectionMicrosurfaceInfos;
+	uniform float fFovMultiplier;
 
 	uniform float pointSize;
 	uniform float shadowLevel;

+ 1 - 0
src/Shaders/ShadersInclude/backgroundVertexDeclaration.fx

@@ -11,6 +11,7 @@ uniform vec2 vDiffuseInfos;
     uniform vec2 vReflectionInfos;
     uniform mat4 reflectionMatrix;
     uniform vec3 vReflectionMicrosurfaceInfos;
+    uniform float fFovMultiplier;
 #endif
 
 #ifdef POINTSIZE

+ 5 - 0
src/Shaders/ShadersInclude/defaultFragmentDeclaration.fx

@@ -75,6 +75,11 @@ uniform vec2 vReflectionInfos;
 #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)
 uniform mat4 reflectionMatrix;
 #endif
+
+#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
+	uniform vec3 vReflectionPosition;
+	uniform vec3 vReflectionSize; 
+#endif
 #endif
 
 #ifdef REFLECTIONFRESNEL

+ 0 - 0
src/Shaders/ShadersInclude/defaultUboDeclaration.fx


Some files were not shown because too many files changed in this diff