Pārlūkot izejas kodu

revert wrong commit of everything...

nockawa 9 gadi atpakaļ
vecāks
revīzija
3eab76506f
100 mainītis faili ar 22150 papildinājumiem un 21169 dzēšanām
  1. 0 27
      .gitignore
  2. 0 95
      Libs/dat.gui.min.js
  3. 743 0
      loaders/OBJ/babylon.objFileLoader.js
  4. 81 0
      loaders/STL/babylon.stlFileLoader.js
  5. 1561 0
      loaders/glTF/babylon.glTFFileLoader.js
  6. 1 0
      loaders/glTF/babylon.glTFFileLoaderInterfaces.js
  7. 88 0
      serializers/OBJ/babylon.objSerializer.js
  8. 131 132
      src/Actions/babylon.action.js
  9. 527 528
      src/Actions/babylon.actionManager.js
  10. 157 158
      src/Actions/babylon.condition.js
  11. 303 304
      src/Actions/babylon.directActions.js
  12. 77 78
      src/Actions/babylon.interpolateValueAction.js
  13. 132 133
      src/Animations/babylon.animatable.js
  14. 741 742
      src/Animations/babylon.animation.js
  15. 249 250
      src/Animations/babylon.easing.js
  16. 111 112
      src/Audio/babylon.analyser.js
  17. 106 107
      src/Audio/babylon.audioEngine.js
  18. 560 561
      src/Audio/babylon.sound.js
  19. 101 102
      src/Audio/babylon.soundtrack.js
  20. 141 142
      src/Bones/babylon.bone.js
  21. 71 72
      src/Cameras/Inputs/babylon.arcrotatecamera.input.gamepad.js
  22. 113 114
      src/Cameras/Inputs/babylon.arcrotatecamera.input.keyboard.js
  23. 57 58
      src/Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.js
  24. 219 220
      src/Cameras/Inputs/babylon.arcrotatecamera.input.pointers.js
  25. 48 49
      src/Cameras/Inputs/babylon.arcrotatecamera.input.vrdeviceorientation.js
  26. 62 63
      src/Cameras/Inputs/babylon.freecamera.input.deviceorientation.js
  27. 66 67
      src/Cameras/Inputs/babylon.freecamera.input.gamepad.js
  28. 117 118
      src/Cameras/Inputs/babylon.freecamera.input.keyboard.js
  29. 98 99
      src/Cameras/Inputs/babylon.freecamera.input.mouse.js
  30. 122 123
      src/Cameras/Inputs/babylon.freecamera.input.touch.js
  31. 54 55
      src/Cameras/Inputs/babylon.freecamera.input.virtualjoystick.js
  32. 53 54
      src/Cameras/Inputs/babylon.freecamera.input.vrdeviceorientation.js
  33. 72 73
      src/Cameras/VR/babylon.vrCameraMetrics.js
  34. 41 42
      src/Cameras/VR/babylon.vrDeviceOrientationCamera.js
  35. 80 81
      src/Cameras/VR/babylon.webVRCamera.js
  36. 546 547
      src/Cameras/babylon.arcRotateCamera.js
  37. 36 37
      src/Cameras/babylon.arcRotateCameraInputsManager.js
  38. 620 621
      src/Cameras/babylon.camera.js
  39. 133 134
      src/Cameras/babylon.cameraInputsManager.js
  40. 41 42
      src/Cameras/babylon.deviceOrientationCamera.js
  41. 117 118
      src/Cameras/babylon.followCamera.js
  42. 185 186
      src/Cameras/babylon.freeCamera.js
  43. 45 46
      src/Cameras/babylon.freeCameraInputsManager.js
  44. 51 52
      src/Cameras/babylon.gamepadCamera.js
  45. 116 117
      src/Cameras/babylon.stereoscopicCameras.js
  46. 58 59
      src/Cameras/babylon.touchCamera.js
  47. 51 52
      src/Cameras/babylon.universalCamera.js
  48. 18 19
      src/Cameras/babylon.virtualJoysticksCamera.js
  49. 157 158
      src/Canvas2d/babylon.bounding2d.js
  50. 184 185
      src/Canvas2d/babylon.brushes2d.js
  51. 351 331
      src/Canvas2d/babylon.ellipse2d.js
  52. 1088 1127
      src/Canvas2d/babylon.lines2d.js
  53. 311 312
      src/Canvas2d/babylon.modelRenderCache.js
  54. 1016 2181
      src/Canvas2d/babylon.prim2dBase.js
  55. 415 432
      src/Canvas2d/babylon.rectangle2d.js
  56. 248 267
      src/Canvas2d/babylon.shape2d.js
  57. 445 523
      src/Canvas2d/babylon.smartPropertyPrim.js
  58. 355 339
      src/Canvas2d/babylon.sprite2d.js
  59. 390 395
      src/Canvas2d/babylon.text2d.js
  60. 27 28
      src/Canvas2d/babylon.worldSpaceCanvas2d.js
  61. 272 273
      src/Collisions/babylon.collider.js
  62. 273 274
      src/Collisions/babylon.collisionCoordinator.js
  63. 243 244
      src/Collisions/babylon.collisionWorker.js
  64. 76 77
      src/Collisions/babylon.pickingInfo.js
  65. 88 89
      src/Culling/Octrees/babylon.octree.js
  66. 122 123
      src/Culling/Octrees/babylon.octreeBlock.js
  67. 143 144
      src/Culling/babylon.boundingBox.js
  68. 119 120
      src/Culling/babylon.boundingInfo.js
  69. 49 50
      src/Culling/babylon.boundingSphere.js
  70. 274 275
      src/Culling/babylon.ray.js
  71. 679 680
      src/Debug/babylon.debugLayer.js
  72. 137 138
      src/Debug/babylon.skeletonViewer.js
  73. 140 141
      src/Layer/babylon.layer.js
  74. 23 24
      src/LensFlare/babylon.lensFlare.js
  75. 214 215
      src/LensFlare/babylon.lensFlareSystem.js
  76. 407 408
      src/Lights/Shadows/babylon.shadowGenerator.js
  77. 129 130
      src/Lights/babylon.directionalLight.js
  78. 51 52
      src/Lights/babylon.hemisphericLight.js
  79. 194 195
      src/Lights/babylon.light.js
  80. 87 88
      src/Lights/babylon.pointLight.js
  81. 98 99
      src/Lights/babylon.spotLight.js
  82. 491 492
      src/Loading/Plugins/babylon.babylonFileLoader.js
  83. 263 264
      src/Loading/babylon.sceneLoader.js
  84. 124 125
      src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js
  85. 284 285
      src/Materials/Textures/Procedurals/babylon.proceduralTexture.js
  86. 187 188
      src/Materials/Textures/babylon.baseTexture.js
  87. 182 183
      src/Materials/Textures/babylon.colorGradingTexture.js
  88. 82 83
      src/Materials/Textures/babylon.cubeTexture.js
  89. 251 252
      src/Materials/Textures/babylon.fontTexture.js
  90. 447 448
      src/Materials/Textures/babylon.hdrCubeTexture.js
  91. 110 111
      src/Materials/Textures/babylon.mapTexture.js
  92. 54 55
      src/Materials/Textures/babylon.mirrorTexture.js
  93. 57 58
      src/Materials/Textures/babylon.rawTexture.js
  94. 52 53
      src/Materials/Textures/babylon.refractionTexture.js
  95. 334 335
      src/Materials/Textures/babylon.renderTargetTexture.js
  96. 275 276
      src/Materials/Textures/babylon.texture.js
  97. 545 546
      src/Materials/babylon.colorCurves.js
  98. 470 471
      src/Materials/babylon.effect.js
  99. 37 38
      src/Materials/babylon.fresnelParameters.js
  100. 0 0
      src/Materials/babylon.material.js

+ 0 - 27
.gitignore

@@ -58,8 +58,6 @@ ipch/
 # ReSharper is a .NET coding add-in
 _ReSharper*
 
-/src/**/*.js
-
 # NCrunch
 *.ncrunch*
 .*crunch*.local.xml
@@ -130,28 +128,3 @@ node_modules
 
 # for VSCode
 .vscode
-/typescript/SymbolicVisualHelper.ts
-/typescript/SymbolicVisualHelper.js
-/typescript/SimpleInteractionHelper.ts
-/typescript/simpleinteractionhelper.js
-/typescript/Radix.ts
-/typescript/Radix.js
-/typescript/ManipulatorInteractionHelper.ts
-/typescript/ManipulatorInteractionHelper.js
-/typescript/Manipulator.js
-/typescript/MainClass.ts
-/typescript/MainClass.js
-/Web.Release.config
-/Web.Debug.config
-/Web.config
-/tsconfig.json
-/packages.config
-/index.html
-/Babylon.js.sln
-/Babylon.js.csproj
-/src/Canvas2d/babylon.lines2d.js
-/src/Canvas2d/babylon.ellipse2d.js
-/Properties/AssemblyInfo.cs
-/assets
-/.vs/config
-/Typings

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 95
Libs/dat.gui.min.js


+ 743 - 0
loaders/OBJ/babylon.objFileLoader.js

@@ -0,0 +1,743 @@
+
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Class reading and parsing the MTL file bundled with the obj file.
+     */
+    var MTLFileLoader = (function () {
+        function MTLFileLoader() {
+            // All material loaded from the mtl will be set here
+            this.materials = [];
+            /**
+             * This function will read the mtl file and create each material described inside
+             * This function could be improve by adding :
+             * -some component missing (Ni, Tf...)
+             * -including the specific options available
+             *
+             * @param scene
+             * @param data
+             * @param rootUrl
+             */
+            this.parseMTL = function (scene, data, rootUrl) {
+                //Split the lines from the file
+                var lines = data.split('\n');
+                //Space char
+                var delimiter_pattern = /\s+/;
+                //Array with RGB colors
+                var color;
+                //New material
+                var material;
+                //Look at each line
+                for (var i = 0; i < lines.length; i++) {
+                    var line = lines[i].trim();
+                    // Blank line or comment
+                    if (line.length === 0 || line.charAt(0) === '#') {
+                        continue;
+                    }
+                    //Get the first parameter (keyword)
+                    var pos = line.indexOf(' ');
+                    var key = (pos >= 0) ? line.substring(0, pos) : line;
+                    key = key.toLowerCase();
+                    //Get the data following the key
+                    var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
+                    //This mtl keyword will create the new material
+                    if (key === "newmtl") {
+                        //Check if it is the first material.
+                        // Materials specifications are described after this keyword.
+                        if (material) {
+                            //Add the previous material in the material array.
+                            this.materials.push(material);
+                        }
+                        //Create a new material.
+                        // value is the name of the material read in the mtl file
+                        material = new BABYLON.StandardMaterial(value, scene);
+                    }
+                    else if (key === "kd") {
+                        // Diffuse color (color under white light) using RGB values
+                        //value  = "r g b"
+                        color = value.split(delimiter_pattern, 3);
+                        //color = [r,g,b]
+                        //Set tghe color into the material
+                        material.diffuseColor = BABYLON.Color3.FromArray(color);
+                    }
+                    else if (key === "ka") {
+                        // Ambient color (color under shadow) using RGB values
+                        //value = "r g b"
+                        color = value.split(delimiter_pattern, 3);
+                        //color = [r,g,b]
+                        //Set tghe color into the material
+                        material.ambientColor = BABYLON.Color3.FromArray(color);
+                    }
+                    else if (key === "ks") {
+                        // Specular color (color when light is reflected from shiny surface) using RGB values
+                        //value = "r g b"
+                        color = value.split(delimiter_pattern, 3);
+                        //color = [r,g,b]
+                        //Set the color into the material
+                        material.specularColor = BABYLON.Color3.FromArray(color);
+                    }
+                    else if (key === "ns") {
+                        //value = "Integer"
+                        material.specularPower = value;
+                    }
+                    else if (key === "d") {
+                        //d is dissolve for current material. It mean alpha for BABYLON
+                        material.alpha = value;
+                    }
+                    else if (key === "map_ka") {
+                        // ambient texture map with a loaded image
+                        //We must first get the folder of the image
+                        material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
+                    }
+                    else if (key === "map_kd") {
+                        // Diffuse texture map with a loaded image
+                        material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
+                    }
+                    else if (key === "map_ks") {
+                        // Specular texture map with a loaded image
+                        //We must first get the folder of the image
+                        material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
+                    }
+                    else if (key === "map_ns") {
+                    }
+                    else if (key === "map_bump") {
+                        //The bump texture
+                        material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
+                    }
+                    else if (key === "map_d") {
+                        // The dissolve of the material
+                        material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
+                    }
+                    else if (key === "illum") {
+                        //Illumination
+                        if (value === "0") {
+                        }
+                        else if (value === "1") {
+                        }
+                        else if (value === "2") {
+                        }
+                        else if (value === "3") {
+                        }
+                        else if (value === "4") {
+                        }
+                        else if (value === "5") {
+                        }
+                        else if (value === "6") {
+                        }
+                        else if (value === "7") {
+                        }
+                        else if (value === "8") {
+                        }
+                        else if (value === "9") {
+                        }
+                        else if (value === "10") {
+                        }
+                    }
+                    else {
+                    }
+                }
+                //At the end of the file, add the last material
+                this.materials.push(material);
+            };
+        }
+        /**
+         * Gets the texture for the material.
+         *
+         * If the material is imported from input file,
+         * We sanitize the url to ensure it takes the textre from aside the material.
+         *
+         * @param rootUrl The root url to load from
+         * @param value The value stored in the mtl
+         * @return The Texture
+         */
+        MTLFileLoader._getTexture = function (rootUrl, value, scene) {
+            var url = rootUrl;
+            // Load from input file.
+            if (rootUrl === "file:") {
+                var lastDelimiter = value.lastIndexOf("\\");
+                if (lastDelimiter === -1) {
+                    lastDelimiter = value.lastIndexOf("/");
+                }
+                if (lastDelimiter > -1) {
+                    url += value.substr(lastDelimiter + 1);
+                }
+                else {
+                    url += value;
+                }
+            }
+            else {
+                url += value;
+            }
+            return new BABYLON.Texture(url, scene);
+        };
+        return MTLFileLoader;
+    }());
+    BABYLON.MTLFileLoader = MTLFileLoader;
+    var OBJFileLoader = (function () {
+        function OBJFileLoader() {
+            this.extensions = ".obj";
+            this.obj = /^o/;
+            this.group = /^g/;
+            this.mtllib = /^mtllib /;
+            this.usemtl = /^usemtl /;
+            this.smooth = /^s /;
+            this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
+            // vn float float float
+            this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
+            // vt float float
+            this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
+            // f vertex vertex vertex ...
+            this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
+            // f vertex/uvs vertex/uvs vertex/uvs ...
+            this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
+            // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
+            this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
+            // f vertex//normal vertex//normal vertex//normal ...
+            this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
+        }
+        /**
+         * Calls synchronously the MTL file attached to this obj.
+         * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
+         * Without this function materials are not displayed in the first frame (but displayed after).
+         * In consequence it is impossible to get material information in your HTML file
+         *
+         * @param url The URL of the MTL file
+         * @param rootUrl
+         * @param onSuccess Callback function to be called when the MTL file is loaded
+         * @private
+         */
+        OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
+            //The complete path to the mtl file
+            var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
+            // Loads through the babylon tools to allow fileInput search.
+            BABYLON.Tools.LoadFile(pathOfFile, onSuccess, null, null, false, function () { console.warn("Error - Unable to load " + pathOfFile); }, true /* synchronous call */);
+        };
+        OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
+            //get the meshes from OBJ file
+            var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
+            //Push meshes from OBJ file into the variable mesh of this function
+            if (meshes) {
+                loadedMeshes.forEach(function (mesh) {
+                    meshes.push(mesh);
+                });
+            }
+            return true;
+        };
+        OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
+            //Get the 3D model
+            return this.importMesh(null, scene, data, rootUrl, null, null, null);
+        };
+        /**
+         * Read the OBJ file and create an Array of meshes.
+         * Each mesh contains all information given by the OBJ and the MTL file.
+         * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
+         *
+         * @param meshesNames
+         * @param scene BABYLON.Scene The scene where are displayed the data
+         * @param data String The content of the obj file
+         * @param rootUrl String The path to the folder
+         * @returns Array<AbstractMesh>
+         * @private
+         */
+        OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
+            var positions = []; //values for the positions of vertices
+            var normals = []; //Values for the normals
+            var uvs = []; //Values for the textures
+            var meshesFromObj = []; //[mesh] Contains all the obj meshes
+            var handledMesh; //The current mesh of meshes array
+            var indicesForBabylon = []; //The list of indices for VertexData
+            var wrappedPositionForBabylon = []; //The list of position in vectors
+            var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
+            var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
+            var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV  [pos, norm, uvs]
+            var curPositionInIndices = 0;
+            var hasMeshes = false; //Meshes are defined in the file
+            var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
+            var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3()  [x,y,z]
+            var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3()      [x,y,z]
+            var triangles = []; //Indices from new triangles coming from polygons
+            var materialNameFromObj = ""; //The name of the current material
+            var fileToLoad = ""; //The name of the mtlFile to load
+            var materialsFromMTLFile = new MTLFileLoader();
+            var objMeshName = ""; //The name of the current obj mesh
+            var increment = 1; //Id for meshes created by the multimaterial
+            var isFirstMaterial = true;
+            /**
+             * Search for obj in the given array.
+             * This function is called to check if a couple of data already exists in an array.
+             *
+             * If found, returns the index of the founded tuple index. Returns -1 if not found
+             * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
+             * @param obj Array<number>
+             * @returns {boolean}
+             */
+            var isInArray = function (arr, obj) {
+                if (!arr[obj[0]])
+                    arr[obj[0]] = { normals: [], idx: [] };
+                var idx = arr[obj[0]].normals.indexOf(obj[1]);
+                return idx === -1 ? -1 : arr[obj[0]].idx[idx];
+            };
+            var isInArrayUV = function (arr, obj) {
+                if (!arr[obj[0]])
+                    arr[obj[0]] = { normals: [], idx: [], uv: [] };
+                var idx = arr[obj[0]].normals.indexOf(obj[1]);
+                if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
+                    return arr[obj[0]].idx[idx];
+                }
+                return -1;
+            };
+            /**
+             * This function set the data for each triangle.
+             * Data are position, normals and uvs
+             * If a tuple of (position, normal) is not set, add the data into the corresponding array
+             * If the tuple already exist, add only their indice
+             *
+             * @param indicePositionFromObj Integer The index in positions array
+             * @param indiceUvsFromObj Integer The index in uvs array
+             * @param indiceNormalFromObj Integer The index in normals array
+             * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
+             * @param textureVectorFromOBJ Vector3 The value of uvs
+             * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
+             */
+            var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
+                //Check if this tuple already exists in the list of tuples
+                var _index;
+                if (OBJFileLoader.OPTIMIZE_WITH_UV) {
+                    _index = isInArrayUV(tuplePosNorm, [
+                        indicePositionFromObj,
+                        indiceNormalFromObj,
+                        indiceUvsFromObj
+                    ]);
+                }
+                else {
+                    _index = isInArray(tuplePosNorm, [
+                        indicePositionFromObj,
+                        indiceNormalFromObj
+                    ]);
+                }
+                //If it not exists
+                if (_index == -1) {
+                    //Add an new indice.
+                    //The array of indices is only an array with his length equal to the number of triangles - 1.
+                    //We add vertices data in this order
+                    indicesForBabylon.push(wrappedPositionForBabylon.length);
+                    //Push the position of vertice for Babylon
+                    //Each element is a BABYLON.Vector3(x,y,z)
+                    wrappedPositionForBabylon.push(positionVectorFromOBJ);
+                    //Push the uvs for Babylon
+                    //Each element is a BABYLON.Vector3(u,v)
+                    wrappedUvsForBabylon.push(textureVectorFromOBJ);
+                    //Push the normals for Babylon
+                    //Each element is a BABYLON.Vector3(x,y,z)
+                    wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
+                    //Add the tuple in the comparison list
+                    tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
+                    tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
+                    if (OBJFileLoader.OPTIMIZE_WITH_UV)
+                        tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
+                }
+                else {
+                    //The tuple already exists
+                    //Add the index of the already existing tuple
+                    //At this index we can get the value of position, normal and uvs of vertex
+                    indicesForBabylon.push(_index);
+                }
+            };
+            /**
+             * Transform BABYLON.Vector() object onto 3 digits in an array
+             */
+            var unwrapData = function () {
+                //Every array has the same length
+                for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
+                    //Push the x, y, z values of each element in the unwrapped array
+                    unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
+                    unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
+                    unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
+                }
+				// Reset arrays for the next new meshes
+                wrappedPositionForBabylon = [];
+                wrappedNormalsForBabylon = [];
+                wrappedUvsForBabylon = [];
+                tuplePosNorm = [];
+                curPositionInIndices = 0;
+                
+            };
+            /**
+             * Create triangles from polygons by recursion
+             * The best to understand how it works is to draw it in the same time you get the recursion.
+             * It is important to notice that a triangle is a polygon
+             * We get 4 patterns of face defined in OBJ File :
+             * facePattern1 = ["1","2","3","4","5","6"]
+             * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
+             * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
+             * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
+             * Each pattern is divided by the same method
+             * @param face Array[String] The indices of elements
+             * @param v Integer The variable to increment
+             */
+            var getTriangles = function (face, v) {
+                //Work for each element of the array
+                if (v + 1 < face.length) {
+                    //Add on the triangle variable the indexes to obtain triangles
+                    triangles.push(face[0], face[v], face[v + 1]);
+                    //Incrementation for recursion
+                    v += 1;
+                    //Recursion
+                    getTriangles(face, v);
+                }
+                //Result obtained after 2 iterations:
+                //Pattern1 => triangle = ["1","2","3","1","3","4"];
+                //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
+                //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
+                //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
+            };
+            /**
+             * Create triangles and push the data for each polygon for the pattern 1
+             * In this pattern we get vertice positions
+             * @param face
+             * @param v
+             */
+            var setDataForCurrentFaceWithPattern1 = function (face, v) {
+                //Get the indices of triangles for each polygon
+                getTriangles(face, v);
+                //For each element in the triangles array.
+                //This var could contains 1 to an infinity of triangles
+                for (var k = 0; k < triangles.length; k++) {
+                    // Set position indice
+                    var indicePositionFromObj = parseInt(triangles[k]) - 1;
+                    setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
+                    positions[indicePositionFromObj], //Get the vectors data
+                    BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
+                    );
+                }
+                //Reset variable for the next line
+                triangles = [];
+            };
+            /**
+             * Create triangles and push the data for each polygon for the pattern 2
+             * In this pattern we get vertice positions and uvsu
+             * @param face
+             * @param v
+             */
+            var setDataForCurrentFaceWithPattern2 = function (face, v) {
+                //Get the indices of triangles for each polygon
+                getTriangles(face, v);
+                for (var k = 0; k < triangles.length; k++) {
+                    //triangle[k] = "1/1"
+                    //Split the data for getting position and uv
+                    var point = triangles[k].split("/"); // ["1", "1"]
+                    //Set position indice
+                    var indicePositionFromObj = parseInt(point[0]) - 1;
+                    //Set uv indice
+                    var indiceUvsFromObj = parseInt(point[1]) - 1;
+                    setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
+                    positions[indicePositionFromObj], //Get the values for each element
+                    uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
+                    );
+                }
+                //Reset variable for the next line
+                triangles = [];
+            };
+            /**
+             * Create triangles and push the data for each polygon for the pattern 3
+             * In this pattern we get vertice positions, uvs and normals
+             * @param face
+             * @param v
+             */
+            var setDataForCurrentFaceWithPattern3 = function (face, v) {
+                //Get the indices of triangles for each polygon
+                getTriangles(face, v);
+                for (var k = 0; k < triangles.length; k++) {
+                    //triangle[k] = "1/1/1"
+                    //Split the data for getting position, uv, and normals
+                    var point = triangles[k].split("/"); // ["1", "1", "1"]
+                    // Set position indice
+                    var indicePositionFromObj = parseInt(point[0]) - 1;
+                    // Set uv indice
+                    var indiceUvsFromObj = parseInt(point[1]) - 1;
+                    // Set normal indice
+                    var indiceNormalFromObj = parseInt(point[2]) - 1;
+                    setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
+                    );
+                }
+                //Reset variable for the next line
+                triangles = [];
+            };
+            /**
+             * Create triangles and push the data for each polygon for the pattern 4
+             * In this pattern we get vertice positions and normals
+             * @param face
+             * @param v
+             */
+            var setDataForCurrentFaceWithPattern4 = function (face, v) {
+                getTriangles(face, v);
+                for (var k = 0; k < triangles.length; k++) {
+                    //triangle[k] = "1//1"
+                    //Split the data for getting position and normals
+                    var point = triangles[k].split("//"); // ["1", "1"]
+                    // We check indices, and normals
+                    var indicePositionFromObj = parseInt(point[0]) - 1;
+                    var indiceNormalFromObj = parseInt(point[1]) - 1;
+                    setData(indicePositionFromObj, 1, //Default value for uv
+                    indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
+                    BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
+                }
+                //Reset variable for the next line
+                triangles = [];
+            };
+            var addPreviousObjMesh = function () {
+                //Check if it is not the first mesh. Otherwise we don't have data.
+                if (meshesFromObj.length > 0) {
+                    //Get the previous mesh for applying the data about the faces
+                    //=> in obj file, faces definition append after the name of the mesh
+                    handledMesh = meshesFromObj[meshesFromObj.length - 1];
+                    //Set the data into Array for the mesh
+                    unwrapData();
+                    // Reverse tab. Otherwise face are displayed in the wrong sens
+                    indicesForBabylon.reverse();
+                    //Set the information for the mesh
+                    //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
+                    handledMesh.indices = indicesForBabylon.slice();
+                    handledMesh.positions = unwrappedPositionsForBabylon.slice();
+                    handledMesh.normals = unwrappedNormalsForBabylon.slice();
+                    handledMesh.uvs = unwrappedUVForBabylon.slice();
+                    //Reset the array for the next mesh
+                    indicesForBabylon = [];
+                    unwrappedPositionsForBabylon = [];
+                    unwrappedNormalsForBabylon = [];
+                    unwrappedUVForBabylon = [];  
+                }
+            };
+            //Main function
+            //Split the file into lines
+            var lines = data.split('\n');
+            //Look at each line
+            for (var i = 0; i < lines.length; i++) {
+                var line = lines[i].trim();
+                var result;
+                //Comment or newLine
+                if (line.length === 0 || line.charAt(0) === '#') {
+                    continue;
+                }
+                else if ((result = this.vertexPattern.exec(line)) !== null) {
+                    //Create a Vector3 with the position x, y, z
+                    //Value of result:
+                    // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
+                    //Add the Vector in the list of positions
+                    positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
+                }
+                else if ((result = this.normalPattern.exec(line)) !== null) {
+                    //Create a Vector3 with the normals x, y, z
+                    //Value of result
+                    // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
+                    //Add the Vector in the list of normals
+                    normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
+                }
+                else if ((result = this.uvPattern.exec(line)) !== null) {
+                    //Create a Vector2 with the normals u, v
+                    //Value of result
+                    // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
+                    //Add the Vector in the list of uvs
+                    uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
+                }
+                else if ((result = this.facePattern3.exec(line)) !== null) {
+                    //Value of result:
+                    //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
+                    //Set the data for this face
+                    setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
+                    1);
+                }
+                else if ((result = this.facePattern4.exec(line)) !== null) {
+                    //Value of result:
+                    //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
+                    //Set the data for this face
+                    setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
+                    1);
+                }
+                else if ((result = this.facePattern2.exec(line)) !== null) {
+                    //Value of result:
+                    //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
+                    //Set the data for this face
+                    setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
+                    1);
+                }
+                else if ((result = this.facePattern1.exec(line)) !== null) {
+                    //Value of result
+                    //["f 1 2 3", "1 2 3"...]
+                    //Set the data for this face
+                    setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
+                    1);
+                }
+                else if (this.group.test(line) || this.obj.test(line)) {
+                    //Create a new mesh corresponding to the name of the group.
+                    //Definition of the mesh
+                    var objMesh = 
+                    //Set the name of the current obj mesh
+                    {
+                        name: line.substring(2).trim(),
+                        indices: undefined,
+                        positions: undefined,
+                        normals: undefined,
+                        uvs: undefined,
+                        materialName: ""
+                    };
+                    addPreviousObjMesh();
+                    //Push the last mesh created with only the name
+                    meshesFromObj.push(objMesh);
+                    //Set this variable to indicate that now meshesFromObj has objects defined inside
+                    hasMeshes = true;
+                    isFirstMaterial = true;
+                    increment = 1;
+                }
+                else if (this.usemtl.test(line)) {
+                    //Get the name of the material
+                    materialNameFromObj = line.substring(7).trim();
+                    //If this new material is in the same mesh
+                    if (!isFirstMaterial) {
+                        //Set the data for the previous mesh
+                        addPreviousObjMesh();
+                        //Create a new mesh
+                        var objMesh = 
+                        //Set the name of the current obj mesh
+                        {
+                            name: objMeshName + "_mm" + increment.toString(),
+                            indices: undefined,
+                            positions: undefined,
+                            normals: undefined,
+                            uvs: undefined,
+                            materialName: materialNameFromObj
+                        };
+                        increment++;
+                        //If meshes are already defined
+                        meshesFromObj.push(objMesh);
+                    }
+                    //Set the material name if the previous line define a mesh
+                    if (hasMeshes && isFirstMaterial) {
+                        //Set the material name to the previous mesh (1 material per mesh)
+                        meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
+                        isFirstMaterial = false;
+                    }
+                }
+                else if (this.mtllib.test(line)) {
+                    //Get the name of mtl file
+                    fileToLoad = line.substring(7).trim();
+                }
+                else if (this.smooth.test(line)) {
+                }
+                else {
+                    //If there is another possibility
+                    console.log("Unhandled expression at line : " + line);
+                }
+            }
+            //At the end of the file, add the last mesh into the meshesFromObj array
+            if (hasMeshes) {
+                //Set the data for the last mesh
+                handledMesh = meshesFromObj[meshesFromObj.length - 1];
+                //Reverse indices for displaying faces in the good sens
+                indicesForBabylon.reverse();
+                //Get the good array
+                unwrapData();
+                //Set array
+                handledMesh.indices = indicesForBabylon;
+                handledMesh.positions = unwrappedPositionsForBabylon;
+                handledMesh.normals = unwrappedNormalsForBabylon;
+                handledMesh.uvs = unwrappedUVForBabylon;
+            }
+            //If any o or g keyword found, create a mesj with a random id
+            if (!hasMeshes) {
+                // reverse tab of indices
+                indicesForBabylon.reverse();
+                //Get positions normals uvs
+                unwrapData();
+                //Set data for one mesh
+                meshesFromObj.push({
+                    name: BABYLON.Geometry.RandomId(),
+                    indices: indicesForBabylon,
+                    positions: unwrappedPositionsForBabylon,
+                    normals: unwrappedNormalsForBabylon,
+                    uvs: unwrappedUVForBabylon,
+                    materialName: materialNameFromObj
+                });
+            }
+            //Create a BABYLON.Mesh list
+            var babylonMeshesArray = []; //The mesh for babylon
+            var materialToUse = [];
+            //Set data for each mesh
+            for (var j = 0; j < meshesFromObj.length; j++) {
+                //check meshesNames (stlFileLoader)
+                if (meshesNames && meshesFromObj[j].name) {
+                    if (meshesNames instanceof Array) {
+                        if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
+                            continue;
+                        }
+                    }
+                    else {
+                        if (meshesFromObj[j].name !== meshesNames) {
+                            continue;
+                        }
+                    }
+                }
+                //Get the current mesh
+                //Set the data with VertexBuffer for each mesh
+                handledMesh = meshesFromObj[j];
+                //Create a BABYLON.Mesh with the name of the obj mesh
+                var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
+                //Push the name of the material to an array
+                //This is indispensable for the importMesh function
+                materialToUse.push(meshesFromObj[j].materialName);
+                //Set the data for the babylonMesh
+                
+                var vertexData = new BABYLON.VertexData(); //The container for the values
+                vertexData.positions = handledMesh.positions;
+                vertexData.normals = handledMesh.normals;
+                vertexData.uvs = handledMesh.uvs;
+                vertexData.indices = handledMesh.indices;
+                //Set the data from the VertexBuffer to the current BABYLON.Mesh
+                vertexData.applyToMesh(babylonMesh);
+                //Push the mesh into an array
+                babylonMeshesArray.push(babylonMesh);
+            }
+            //load the materials
+            //Check if we have a file to load
+            if (fileToLoad !== "") {
+                //Load the file synchronously
+                this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
+                    //Create materials thanks MTLLoader function
+                    materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
+                    //Look at each material loaded in the mtl file
+                    for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
+                        //Three variables to get all meshes with the same material
+                        var startIndex = 0;
+                        var _indices = [];
+                        var _index;
+                        //The material from MTL file is used in the meshes loaded
+                        //Push the indice in an array
+                        //Check if the material is not used for another mesh
+                        while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
+                            _indices.push(_index);
+                            startIndex = _index + 1;
+                        }
+                        //If the material is not used dispose it
+                        if (_index == -1 && _indices.length == 0) {
+                            //If the material is not needed, remove it
+                            materialsFromMTLFile.materials[n].dispose();
+                        }
+                        else {
+                            for (var o = 0; o < _indices.length; o++) {
+                                //Apply the material to the BABYLON.Mesh for each mesh with the material
+                                babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
+                            }
+                        }
+                    }
+                });
+            }
+            //Return an array with all BABYLON.Mesh
+            return babylonMeshesArray;
+        };
+        OBJFileLoader.OPTIMIZE_WITH_UV = false;
+        return OBJFileLoader;
+    }());
+    BABYLON.OBJFileLoader = OBJFileLoader;
+    //Add this loader into the register plugin
+    BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
+})(BABYLON || (BABYLON = {}));

+ 81 - 0
loaders/STL/babylon.stlFileLoader.js

@@ -0,0 +1,81 @@
+var BABYLON;
+(function (BABYLON) {
+    var STLFileLoader = (function () {
+        function STLFileLoader() {
+            this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
+            this.facetsPattern = /facet([\s\S]*?)endfacet/g;
+            this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
+            this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
+            this.extensions = ".stl";
+        }
+        STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
+            var matches;
+            while (matches = this.solidPattern.exec(data)) {
+                var meshName = matches[1];
+                var meshNameFromEnd = matches[3];
+                if (meshName != meshNameFromEnd) {
+                    console.log("error in stl, solid name != endsolid name");
+                }
+                //check meshesNames
+                if (meshesNames && meshName) {
+                    if (meshesNames instanceof Array) {
+                        if (!meshesNames.indexOf(meshName)) {
+                            continue;
+                        }
+                    }
+                    else {
+                        if (meshName !== meshesNames) {
+                            continue;
+                        }
+                    }
+                }
+                //stl mesh name can be empty as well
+                meshName = meshName || "stlmesh";
+                var babylonMesh = new BABYLON.Mesh(meshName, scene);
+                this.parseSolid(babylonMesh, matches[2]);
+            }
+            return true;
+        };
+        STLFileLoader.prototype.load = function (scene, data, rootUrl) {
+            var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
+            if (result) {
+                scene.createDefaultCameraOrLight();
+            }
+            return result;
+        };
+        STLFileLoader.prototype.parseSolid = function (mesh, solidData) {
+            var normals = [];
+            var positions = [];
+            var indices = [];
+            var indicesCount = 0;
+            //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
+            var matches;
+            while (matches = this.facetsPattern.exec(solidData)) {
+                var facet = matches[1];
+                //one normal per face
+                var normalMatches = this.normalPattern.exec(facet);
+                this.normalPattern.lastIndex = 0;
+                if (!normalMatches) {
+                    continue;
+                }
+                var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
+                var vertexMatch;
+                while (vertexMatch = this.vertexPattern.exec(facet)) {
+                    positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
+                    normals.push(normal[0], normal[1], normal[2]);
+                }
+                indices.push(indicesCount++, indicesCount++, indicesCount++);
+                this.vertexPattern.lastIndex = 0;
+            }
+            this.facetsPattern.lastIndex = 0;
+            mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
+            mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
+            mesh.setIndices(indices);
+            mesh.computeWorldMatrix(true);
+        };
+        return STLFileLoader;
+    })();
+    BABYLON.STLFileLoader = STLFileLoader;
+    BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.stlFileLoader.js.map

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1561 - 0
loaders/glTF/babylon.glTFFileLoader.js


+ 1 - 0
loaders/glTF/babylon.glTFFileLoaderInterfaces.js

@@ -0,0 +1 @@
+//# sourceMappingURL=babylon.glTFFileLoaderInterfaces.js.map

+ 88 - 0
serializers/OBJ/babylon.objSerializer.js

@@ -0,0 +1,88 @@
+/// <reference path="../babylon.d.ts"/>
+var BABYLON;
+(function (BABYLON) {
+    var OBJExport = (function () {
+        function OBJExport() {
+        }
+        //Exports the geometry of a Mesh in .OBJ file format (text)
+        OBJExport.OBJ = function (mesh, materials, matlibname) {
+            var output = [];
+            var g = mesh.geometry;
+            var trunkVerts = g.getVerticesData('position');
+            var trunkNormals = g.getVerticesData('normal');
+            var trunkUV = g.getVerticesData('uv');
+            var trunkFaces = g.getIndices();
+            if (materials) {
+                if (!matlibname) {
+                    matlibname = 'mat';
+                }
+                output.push("mtllib " + matlibname + ".mtl");
+            }
+            for (var i = 0; i < trunkVerts.length; i += 3) {
+                output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
+            }
+            for (i = 0; i < trunkNormals.length; i += 3) {
+                output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
+            }
+            for (i = 0; i < trunkUV.length; i += 2) {
+                output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
+            }
+            //TODO: submeshes (groups)
+            //TODO: smoothing groups (s 1, s off)
+            output.push("g gr1");
+            if (materials) {
+                output.push("usemtl mat1");
+            }
+            for (i = 0; i < trunkFaces.length; i += 3) {
+                output.push("f " + (trunkFaces[i + 2] + 1) + "/" + (trunkFaces[i + 2] + 1) + "/" + (trunkFaces[i + 2] + 1) +
+                    " " + (trunkFaces[i + 1] + 1) + "/" + (trunkFaces[i + 1] + 1) + "/" + (trunkFaces[i + 1] + 1) +
+                    " " + (trunkFaces[i] + 1) + "/" + (trunkFaces[i] + 1) + "/" + (trunkFaces[i] + 1));
+            }
+            var text = output.join("\n");
+            return (text);
+        };
+        //Exports the material(s) of a mesh in .MTL file format (text)
+        OBJExport.MTL = function (mesh) {
+            var output = [];
+            var m = mesh.material;
+            output.push("newmtl mat1");
+            output.push("  Ns " + m.specularPower.toFixed(4));
+            output.push("  Ni 1.5000");
+            output.push("  d " + m.alpha.toFixed(4));
+            output.push("  Tr 0.0000");
+            output.push("  Tf 1.0000 1.0000 1.0000");
+            output.push("  illum 2");
+            output.push("  Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
+            output.push("  Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
+            output.push("  Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
+            output.push("  Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
+            //TODO: uv scale, offset, wrap
+            //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
+            var uvscale = "";
+            if (m.ambientTexture) {
+                output.push("  map_Ka " + uvscale + m.ambientTexture.name);
+            }
+            if (m.diffuseTexture) {
+                output.push("  map_Kd " + uvscale + m.diffuseTexture.name);
+            }
+            if (m.specularTexture) {
+                output.push("  map_Ks " + uvscale + m.specularTexture.name);
+            }
+            /* TODO: emissive texture not in .MAT format (???)
+            if (m.emissiveTexture) {
+                output.push("  map_d "+uvscale+m.emissiveTexture.name);
+            }
+            */
+            if (m.bumpTexture) {
+                output.push("  map_bump -imfchan z " + uvscale + m.bumpTexture.name);
+            }
+            if (m.opacityTexture) {
+                output.push("  map_d " + uvscale + m.opacityTexture.name);
+            }
+            var text = output.join("\n");
+            return (text);
+        };
+        return OBJExport;
+    })();
+    BABYLON.OBJExport = OBJExport;
+})(BABYLON || (BABYLON = {}));

+ 131 - 132
src/Actions/babylon.action.js

@@ -1,132 +1,131 @@
-var BABYLON;
-(function (BABYLON) {
-    var Action = (function () {
-        function Action(triggerOptions, condition) {
-            this.triggerOptions = triggerOptions;
-            if (triggerOptions.parameter) {
-                this.trigger = triggerOptions.trigger;
-                this._triggerParameter = triggerOptions.parameter;
-            }
-            else {
-                this.trigger = triggerOptions;
-            }
-            this._nextActiveAction = this;
-            this._condition = condition;
-        }
-        // Methods
-        Action.prototype._prepare = function () {
-        };
-        Action.prototype.getTriggerParameter = function () {
-            return this._triggerParameter;
-        };
-        Action.prototype._executeCurrent = function (evt) {
-            if (this._nextActiveAction._condition) {
-                var condition = this._nextActiveAction._condition;
-                var currentRenderId = this._actionManager.getScene().getRenderId();
-                // We cache the current evaluation for the current frame
-                if (condition._evaluationId === currentRenderId) {
-                    if (!condition._currentResult) {
-                        return;
-                    }
-                }
-                else {
-                    condition._evaluationId = currentRenderId;
-                    if (!condition.isValid()) {
-                        condition._currentResult = false;
-                        return;
-                    }
-                    condition._currentResult = true;
-                }
-            }
-            this._nextActiveAction.execute(evt);
-            this.skipToNextActiveAction();
-        };
-        Action.prototype.execute = function (evt) {
-        };
-        Action.prototype.skipToNextActiveAction = function () {
-            if (this._nextActiveAction._child) {
-                if (!this._nextActiveAction._child._actionManager) {
-                    this._nextActiveAction._child._actionManager = this._actionManager;
-                }
-                this._nextActiveAction = this._nextActiveAction._child;
-            }
-            else {
-                this._nextActiveAction = this;
-            }
-        };
-        Action.prototype.then = function (action) {
-            this._child = action;
-            action._actionManager = this._actionManager;
-            action._prepare();
-            return action;
-        };
-        Action.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        Action.prototype.serialize = function (parent) {
-        };
-        // Called by BABYLON.Action objects in serialize(...). Internal use
-        Action.prototype._serialize = function (serializedAction, parent) {
-            var serializationObject = {
-                type: 1,
-                children: [],
-                name: serializedAction.name,
-                properties: serializedAction.properties || []
-            };
-            // Serialize child
-            if (this._child) {
-                this._child.serialize(serializationObject);
-            }
-            // Check if "this" has a condition
-            if (this._condition) {
-                var serializedCondition = this._condition.serialize();
-                serializedCondition.children.push(serializationObject);
-                if (parent) {
-                    parent.children.push(serializedCondition);
-                }
-                return serializedCondition;
-            }
-            if (parent) {
-                parent.children.push(serializationObject);
-            }
-            return serializationObject;
-        };
-        Action._SerializeValueAsString = function (value) {
-            if (typeof value === "number") {
-                return value.toString();
-            }
-            if (typeof value === "boolean") {
-                return value ? "true" : "false";
-            }
-            if (value instanceof BABYLON.Vector2) {
-                return value.x + ", " + value.y;
-            }
-            if (value instanceof BABYLON.Vector3) {
-                return value.x + ", " + value.y + ", " + value.z;
-            }
-            if (value instanceof BABYLON.Color3) {
-                return value.r + ", " + value.g + ", " + value.b;
-            }
-            if (value instanceof BABYLON.Color4) {
-                return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
-            }
-            return value; // string
-        };
-        Action._GetTargetProperty = function (target) {
-            return {
-                name: "target",
-                targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
-                    : target instanceof BABYLON.Light ? "LightProperties"
-                        : target instanceof BABYLON.Camera ? "CameraProperties"
-                            : "SceneProperties",
-                value: target instanceof BABYLON.Scene ? "Scene" : target.name
-            };
-        };
-        return Action;
-    }());
-    BABYLON.Action = Action;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.action.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Action = (function () {
+        function Action(triggerOptions, condition) {
+            this.triggerOptions = triggerOptions;
+            if (triggerOptions.parameter) {
+                this.trigger = triggerOptions.trigger;
+                this._triggerParameter = triggerOptions.parameter;
+            }
+            else {
+                this.trigger = triggerOptions;
+            }
+            this._nextActiveAction = this;
+            this._condition = condition;
+        }
+        // Methods
+        Action.prototype._prepare = function () {
+        };
+        Action.prototype.getTriggerParameter = function () {
+            return this._triggerParameter;
+        };
+        Action.prototype._executeCurrent = function (evt) {
+            if (this._nextActiveAction._condition) {
+                var condition = this._nextActiveAction._condition;
+                var currentRenderId = this._actionManager.getScene().getRenderId();
+                // We cache the current evaluation for the current frame
+                if (condition._evaluationId === currentRenderId) {
+                    if (!condition._currentResult) {
+                        return;
+                    }
+                }
+                else {
+                    condition._evaluationId = currentRenderId;
+                    if (!condition.isValid()) {
+                        condition._currentResult = false;
+                        return;
+                    }
+                    condition._currentResult = true;
+                }
+            }
+            this._nextActiveAction.execute(evt);
+            this.skipToNextActiveAction();
+        };
+        Action.prototype.execute = function (evt) {
+        };
+        Action.prototype.skipToNextActiveAction = function () {
+            if (this._nextActiveAction._child) {
+                if (!this._nextActiveAction._child._actionManager) {
+                    this._nextActiveAction._child._actionManager = this._actionManager;
+                }
+                this._nextActiveAction = this._nextActiveAction._child;
+            }
+            else {
+                this._nextActiveAction = this;
+            }
+        };
+        Action.prototype.then = function (action) {
+            this._child = action;
+            action._actionManager = this._actionManager;
+            action._prepare();
+            return action;
+        };
+        Action.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        Action.prototype.serialize = function (parent) {
+        };
+        // Called by BABYLON.Action objects in serialize(...). Internal use
+        Action.prototype._serialize = function (serializedAction, parent) {
+            var serializationObject = {
+                type: 1,
+                children: [],
+                name: serializedAction.name,
+                properties: serializedAction.properties || []
+            };
+            // Serialize child
+            if (this._child) {
+                this._child.serialize(serializationObject);
+            }
+            // Check if "this" has a condition
+            if (this._condition) {
+                var serializedCondition = this._condition.serialize();
+                serializedCondition.children.push(serializationObject);
+                if (parent) {
+                    parent.children.push(serializedCondition);
+                }
+                return serializedCondition;
+            }
+            if (parent) {
+                parent.children.push(serializationObject);
+            }
+            return serializationObject;
+        };
+        Action._SerializeValueAsString = function (value) {
+            if (typeof value === "number") {
+                return value.toString();
+            }
+            if (typeof value === "boolean") {
+                return value ? "true" : "false";
+            }
+            if (value instanceof BABYLON.Vector2) {
+                return value.x + ", " + value.y;
+            }
+            if (value instanceof BABYLON.Vector3) {
+                return value.x + ", " + value.y + ", " + value.z;
+            }
+            if (value instanceof BABYLON.Color3) {
+                return value.r + ", " + value.g + ", " + value.b;
+            }
+            if (value instanceof BABYLON.Color4) {
+                return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
+            }
+            return value; // string
+        };
+        Action._GetTargetProperty = function (target) {
+            return {
+                name: "target",
+                targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
+                    : target instanceof BABYLON.Light ? "LightProperties"
+                        : target instanceof BABYLON.Camera ? "CameraProperties"
+                            : "SceneProperties",
+                value: target instanceof BABYLON.Scene ? "Scene" : target.name
+            };
+        };
+        return Action;
+    })();
+    BABYLON.Action = Action;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 527 - 528
src/Actions/babylon.actionManager.js


+ 157 - 158
src/Actions/babylon.condition.js

@@ -1,158 +1,157 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Condition = (function () {
-        function Condition(actionManager) {
-            this._actionManager = actionManager;
-        }
-        Condition.prototype.isValid = function () {
-            return true;
-        };
-        Condition.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        Condition.prototype.serialize = function () {
-        };
-        Condition.prototype._serialize = function (serializedCondition) {
-            return {
-                type: 2,
-                children: [],
-                name: serializedCondition.name,
-                properties: serializedCondition.properties
-            };
-        };
-        return Condition;
-    }());
-    BABYLON.Condition = Condition;
-    var ValueCondition = (function (_super) {
-        __extends(ValueCondition, _super);
-        function ValueCondition(actionManager, target, propertyPath, value, operator) {
-            if (operator === void 0) { operator = ValueCondition.IsEqual; }
-            _super.call(this, actionManager);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this.operator = operator;
-            this._target = target;
-            this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        }
-        Object.defineProperty(ValueCondition, "IsEqual", {
-            get: function () {
-                return ValueCondition._IsEqual;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsDifferent", {
-            get: function () {
-                return ValueCondition._IsDifferent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsGreater", {
-            get: function () {
-                return ValueCondition._IsGreater;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsLesser", {
-            get: function () {
-                return ValueCondition._IsLesser;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        ValueCondition.prototype.isValid = function () {
-            switch (this.operator) {
-                case ValueCondition.IsGreater:
-                    return this._effectiveTarget[this._property] > this.value;
-                case ValueCondition.IsLesser:
-                    return this._effectiveTarget[this._property] < this.value;
-                case ValueCondition.IsEqual:
-                case ValueCondition.IsDifferent:
-                    var check;
-                    if (this.value.equals) {
-                        check = this.value.equals(this._effectiveTarget[this._property]);
-                    }
-                    else {
-                        check = this.value === this._effectiveTarget[this._property];
-                    }
-                    return this.operator === ValueCondition.IsEqual ? check : !check;
-            }
-            return false;
-        };
-        ValueCondition.prototype.serialize = function () {
-            return this._serialize({
-                name: "ValueCondition",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "propertyPath", value: this.propertyPath },
-                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
-                    { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
-                ]
-            });
-        };
-        ValueCondition.GetOperatorName = function (operator) {
-            switch (operator) {
-                case ValueCondition._IsEqual: return "IsEqual";
-                case ValueCondition._IsDifferent: return "IsDifferent";
-                case ValueCondition._IsGreater: return "IsGreater";
-                case ValueCondition._IsLesser: return "IsLesser";
-                default: return "";
-            }
-        };
-        // Statics
-        ValueCondition._IsEqual = 0;
-        ValueCondition._IsDifferent = 1;
-        ValueCondition._IsGreater = 2;
-        ValueCondition._IsLesser = 3;
-        return ValueCondition;
-    }(Condition));
-    BABYLON.ValueCondition = ValueCondition;
-    var PredicateCondition = (function (_super) {
-        __extends(PredicateCondition, _super);
-        function PredicateCondition(actionManager, predicate) {
-            _super.call(this, actionManager);
-            this.predicate = predicate;
-        }
-        PredicateCondition.prototype.isValid = function () {
-            return this.predicate();
-        };
-        return PredicateCondition;
-    }(Condition));
-    BABYLON.PredicateCondition = PredicateCondition;
-    var StateCondition = (function (_super) {
-        __extends(StateCondition, _super);
-        function StateCondition(actionManager, target, value) {
-            _super.call(this, actionManager);
-            this.value = value;
-            this._target = target;
-        }
-        // Methods
-        StateCondition.prototype.isValid = function () {
-            return this._target.state === this.value;
-        };
-        StateCondition.prototype.serialize = function () {
-            return this._serialize({
-                name: "StateCondition",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "value", value: this.value }
-                ]
-            });
-        };
-        return StateCondition;
-    }(Condition));
-    BABYLON.StateCondition = StateCondition;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.condition.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Condition = (function () {
+        function Condition(actionManager) {
+            this._actionManager = actionManager;
+        }
+        Condition.prototype.isValid = function () {
+            return true;
+        };
+        Condition.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        Condition.prototype.serialize = function () {
+        };
+        Condition.prototype._serialize = function (serializedCondition) {
+            return {
+                type: 2,
+                children: [],
+                name: serializedCondition.name,
+                properties: serializedCondition.properties
+            };
+        };
+        return Condition;
+    })();
+    BABYLON.Condition = Condition;
+    var ValueCondition = (function (_super) {
+        __extends(ValueCondition, _super);
+        function ValueCondition(actionManager, target, propertyPath, value, operator) {
+            if (operator === void 0) { operator = ValueCondition.IsEqual; }
+            _super.call(this, actionManager);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this.operator = operator;
+            this._target = target;
+            this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        }
+        Object.defineProperty(ValueCondition, "IsEqual", {
+            get: function () {
+                return ValueCondition._IsEqual;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsDifferent", {
+            get: function () {
+                return ValueCondition._IsDifferent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsGreater", {
+            get: function () {
+                return ValueCondition._IsGreater;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsLesser", {
+            get: function () {
+                return ValueCondition._IsLesser;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        ValueCondition.prototype.isValid = function () {
+            switch (this.operator) {
+                case ValueCondition.IsGreater:
+                    return this._effectiveTarget[this._property] > this.value;
+                case ValueCondition.IsLesser:
+                    return this._effectiveTarget[this._property] < this.value;
+                case ValueCondition.IsEqual:
+                case ValueCondition.IsDifferent:
+                    var check;
+                    if (this.value.equals) {
+                        check = this.value.equals(this._effectiveTarget[this._property]);
+                    }
+                    else {
+                        check = this.value === this._effectiveTarget[this._property];
+                    }
+                    return this.operator === ValueCondition.IsEqual ? check : !check;
+            }
+            return false;
+        };
+        ValueCondition.prototype.serialize = function () {
+            return this._serialize({
+                name: "ValueCondition",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "propertyPath", value: this.propertyPath },
+                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
+                    { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
+                ]
+            });
+        };
+        ValueCondition.GetOperatorName = function (operator) {
+            switch (operator) {
+                case ValueCondition._IsEqual: return "IsEqual";
+                case ValueCondition._IsDifferent: return "IsDifferent";
+                case ValueCondition._IsGreater: return "IsGreater";
+                case ValueCondition._IsLesser: return "IsLesser";
+                default: return "";
+            }
+        };
+        // Statics
+        ValueCondition._IsEqual = 0;
+        ValueCondition._IsDifferent = 1;
+        ValueCondition._IsGreater = 2;
+        ValueCondition._IsLesser = 3;
+        return ValueCondition;
+    })(Condition);
+    BABYLON.ValueCondition = ValueCondition;
+    var PredicateCondition = (function (_super) {
+        __extends(PredicateCondition, _super);
+        function PredicateCondition(actionManager, predicate) {
+            _super.call(this, actionManager);
+            this.predicate = predicate;
+        }
+        PredicateCondition.prototype.isValid = function () {
+            return this.predicate();
+        };
+        return PredicateCondition;
+    })(Condition);
+    BABYLON.PredicateCondition = PredicateCondition;
+    var StateCondition = (function (_super) {
+        __extends(StateCondition, _super);
+        function StateCondition(actionManager, target, value) {
+            _super.call(this, actionManager);
+            this.value = value;
+            this._target = target;
+        }
+        // Methods
+        StateCondition.prototype.isValid = function () {
+            return this._target.state === this.value;
+        };
+        StateCondition.prototype.serialize = function () {
+            return this._serialize({
+                name: "StateCondition",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "value", value: this.value }
+                ]
+            });
+        };
+        return StateCondition;
+    })(Condition);
+    BABYLON.StateCondition = StateCondition;
+})(BABYLON || (BABYLON = {}));

+ 303 - 304
src/Actions/babylon.directActions.js

@@ -1,304 +1,303 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var SwitchBooleanAction = (function (_super) {
-        __extends(SwitchBooleanAction, _super);
-        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this._target = this._effectiveTarget = target;
-        }
-        SwitchBooleanAction.prototype._prepare = function () {
-            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        SwitchBooleanAction.prototype.execute = function () {
-            this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
-        };
-        SwitchBooleanAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "SwitchBooleanAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "propertyPath", value: this.propertyPath }
-                ]
-            }, parent);
-        };
-        return SwitchBooleanAction;
-    }(BABYLON.Action));
-    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
-    var SetStateAction = (function (_super) {
-        __extends(SetStateAction, _super);
-        function SetStateAction(triggerOptions, target, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.value = value;
-            this._target = target;
-        }
-        SetStateAction.prototype.execute = function () {
-            this._target.state = this.value;
-        };
-        SetStateAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "SetStateAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "value", value: this.value }
-                ]
-            }, parent);
-        };
-        return SetStateAction;
-    }(BABYLON.Action));
-    BABYLON.SetStateAction = SetStateAction;
-    var SetValueAction = (function (_super) {
-        __extends(SetValueAction, _super);
-        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this._target = this._effectiveTarget = target;
-        }
-        SetValueAction.prototype._prepare = function () {
-            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        SetValueAction.prototype.execute = function () {
-            this._effectiveTarget[this._property] = this.value;
-            if (this._target.markAsDirty) {
-                this._target.markAsDirty(this._property);
-            }
-        };
-        SetValueAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "SetValueAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "propertyPath", value: this.propertyPath },
-                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
-                ]
-            }, parent);
-        };
-        return SetValueAction;
-    }(BABYLON.Action));
-    BABYLON.SetValueAction = SetValueAction;
-    var IncrementValueAction = (function (_super) {
-        __extends(IncrementValueAction, _super);
-        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this._target = this._effectiveTarget = target;
-        }
-        IncrementValueAction.prototype._prepare = function () {
-            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-            if (typeof this._effectiveTarget[this._property] !== "number") {
-                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
-            }
-        };
-        IncrementValueAction.prototype.execute = function () {
-            this._effectiveTarget[this._property] += this.value;
-            if (this._target.markAsDirty) {
-                this._target.markAsDirty(this._property);
-            }
-        };
-        IncrementValueAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "IncrementValueAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "propertyPath", value: this.propertyPath },
-                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
-                ]
-            }, parent);
-        };
-        return IncrementValueAction;
-    }(BABYLON.Action));
-    BABYLON.IncrementValueAction = IncrementValueAction;
-    var PlayAnimationAction = (function (_super) {
-        __extends(PlayAnimationAction, _super);
-        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.from = from;
-            this.to = to;
-            this.loop = loop;
-            this._target = target;
-        }
-        PlayAnimationAction.prototype._prepare = function () {
-        };
-        PlayAnimationAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            scene.beginAnimation(this._target, this.from, this.to, this.loop);
-        };
-        PlayAnimationAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "PlayAnimationAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "from", value: String(this.from) },
-                    { name: "to", value: String(this.to) },
-                    { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
-                ]
-            }, parent);
-        };
-        return PlayAnimationAction;
-    }(BABYLON.Action));
-    BABYLON.PlayAnimationAction = PlayAnimationAction;
-    var StopAnimationAction = (function (_super) {
-        __extends(StopAnimationAction, _super);
-        function StopAnimationAction(triggerOptions, target, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._target = target;
-        }
-        StopAnimationAction.prototype._prepare = function () {
-        };
-        StopAnimationAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            scene.stopAnimation(this._target);
-        };
-        StopAnimationAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "StopAnimationAction",
-                properties: [BABYLON.Action._GetTargetProperty(this._target)]
-            }, parent);
-        };
-        return StopAnimationAction;
-    }(BABYLON.Action));
-    BABYLON.StopAnimationAction = StopAnimationAction;
-    var DoNothingAction = (function (_super) {
-        __extends(DoNothingAction, _super);
-        function DoNothingAction(triggerOptions, condition) {
-            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
-            _super.call(this, triggerOptions, condition);
-        }
-        DoNothingAction.prototype.execute = function () {
-        };
-        DoNothingAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "DoNothingAction",
-                properties: []
-            }, parent);
-        };
-        return DoNothingAction;
-    }(BABYLON.Action));
-    BABYLON.DoNothingAction = DoNothingAction;
-    var CombineAction = (function (_super) {
-        __extends(CombineAction, _super);
-        function CombineAction(triggerOptions, children, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.children = children;
-        }
-        CombineAction.prototype._prepare = function () {
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index]._actionManager = this._actionManager;
-                this.children[index]._prepare();
-            }
-        };
-        CombineAction.prototype.execute = function (evt) {
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index].execute(evt);
-            }
-        };
-        CombineAction.prototype.serialize = function (parent) {
-            var serializationObject = _super.prototype._serialize.call(this, {
-                name: "CombineAction",
-                properties: [],
-                combine: []
-            }, parent);
-            for (var i = 0; i < this.children.length; i++) {
-                serializationObject.combine.push(this.children[i].serialize(null));
-            }
-            return serializationObject;
-        };
-        return CombineAction;
-    }(BABYLON.Action));
-    BABYLON.CombineAction = CombineAction;
-    var ExecuteCodeAction = (function (_super) {
-        __extends(ExecuteCodeAction, _super);
-        function ExecuteCodeAction(triggerOptions, func, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.func = func;
-        }
-        ExecuteCodeAction.prototype.execute = function (evt) {
-            this.func(evt);
-        };
-        return ExecuteCodeAction;
-    }(BABYLON.Action));
-    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
-    var SetParentAction = (function (_super) {
-        __extends(SetParentAction, _super);
-        function SetParentAction(triggerOptions, target, parent, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._target = target;
-            this._parent = parent;
-        }
-        SetParentAction.prototype._prepare = function () {
-        };
-        SetParentAction.prototype.execute = function () {
-            if (this._target.parent === this._parent) {
-                return;
-            }
-            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
-            invertParentWorldMatrix.invert();
-            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
-            this._target.parent = this._parent;
-        };
-        SetParentAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "SetParentAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    BABYLON.Action._GetTargetProperty(this._parent),
-                ]
-            }, parent);
-        };
-        return SetParentAction;
-    }(BABYLON.Action));
-    BABYLON.SetParentAction = SetParentAction;
-    var PlaySoundAction = (function (_super) {
-        __extends(PlaySoundAction, _super);
-        function PlaySoundAction(triggerOptions, sound, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._sound = sound;
-        }
-        PlaySoundAction.prototype._prepare = function () {
-        };
-        PlaySoundAction.prototype.execute = function () {
-            if (this._sound !== undefined)
-                this._sound.play();
-        };
-        PlaySoundAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "PlaySoundAction",
-                properties: [{ name: "sound", value: this._sound.name }]
-            }, parent);
-        };
-        return PlaySoundAction;
-    }(BABYLON.Action));
-    BABYLON.PlaySoundAction = PlaySoundAction;
-    var StopSoundAction = (function (_super) {
-        __extends(StopSoundAction, _super);
-        function StopSoundAction(triggerOptions, sound, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._sound = sound;
-        }
-        StopSoundAction.prototype._prepare = function () {
-        };
-        StopSoundAction.prototype.execute = function () {
-            if (this._sound !== undefined)
-                this._sound.stop();
-        };
-        StopSoundAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "StopSoundAction",
-                properties: [{ name: "sound", value: this._sound.name }]
-            }, parent);
-        };
-        return StopSoundAction;
-    }(BABYLON.Action));
-    BABYLON.StopSoundAction = StopSoundAction;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.directActions.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var SwitchBooleanAction = (function (_super) {
+        __extends(SwitchBooleanAction, _super);
+        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this._target = this._effectiveTarget = target;
+        }
+        SwitchBooleanAction.prototype._prepare = function () {
+            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        SwitchBooleanAction.prototype.execute = function () {
+            this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
+        };
+        SwitchBooleanAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "SwitchBooleanAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "propertyPath", value: this.propertyPath }
+                ]
+            }, parent);
+        };
+        return SwitchBooleanAction;
+    })(BABYLON.Action);
+    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
+    var SetStateAction = (function (_super) {
+        __extends(SetStateAction, _super);
+        function SetStateAction(triggerOptions, target, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.value = value;
+            this._target = target;
+        }
+        SetStateAction.prototype.execute = function () {
+            this._target.state = this.value;
+        };
+        SetStateAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "SetStateAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "value", value: this.value }
+                ]
+            }, parent);
+        };
+        return SetStateAction;
+    })(BABYLON.Action);
+    BABYLON.SetStateAction = SetStateAction;
+    var SetValueAction = (function (_super) {
+        __extends(SetValueAction, _super);
+        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this._target = this._effectiveTarget = target;
+        }
+        SetValueAction.prototype._prepare = function () {
+            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        SetValueAction.prototype.execute = function () {
+            this._effectiveTarget[this._property] = this.value;
+            if (this._target.markAsDirty) {
+                this._target.markAsDirty(this._property);
+            }
+        };
+        SetValueAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "SetValueAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "propertyPath", value: this.propertyPath },
+                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
+                ]
+            }, parent);
+        };
+        return SetValueAction;
+    })(BABYLON.Action);
+    BABYLON.SetValueAction = SetValueAction;
+    var IncrementValueAction = (function (_super) {
+        __extends(IncrementValueAction, _super);
+        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this._target = this._effectiveTarget = target;
+        }
+        IncrementValueAction.prototype._prepare = function () {
+            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+            if (typeof this._effectiveTarget[this._property] !== "number") {
+                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
+            }
+        };
+        IncrementValueAction.prototype.execute = function () {
+            this._effectiveTarget[this._property] += this.value;
+            if (this._target.markAsDirty) {
+                this._target.markAsDirty(this._property);
+            }
+        };
+        IncrementValueAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "IncrementValueAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "propertyPath", value: this.propertyPath },
+                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
+                ]
+            }, parent);
+        };
+        return IncrementValueAction;
+    })(BABYLON.Action);
+    BABYLON.IncrementValueAction = IncrementValueAction;
+    var PlayAnimationAction = (function (_super) {
+        __extends(PlayAnimationAction, _super);
+        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.from = from;
+            this.to = to;
+            this.loop = loop;
+            this._target = target;
+        }
+        PlayAnimationAction.prototype._prepare = function () {
+        };
+        PlayAnimationAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            scene.beginAnimation(this._target, this.from, this.to, this.loop);
+        };
+        PlayAnimationAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "PlayAnimationAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "from", value: String(this.from) },
+                    { name: "to", value: String(this.to) },
+                    { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
+                ]
+            }, parent);
+        };
+        return PlayAnimationAction;
+    })(BABYLON.Action);
+    BABYLON.PlayAnimationAction = PlayAnimationAction;
+    var StopAnimationAction = (function (_super) {
+        __extends(StopAnimationAction, _super);
+        function StopAnimationAction(triggerOptions, target, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._target = target;
+        }
+        StopAnimationAction.prototype._prepare = function () {
+        };
+        StopAnimationAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            scene.stopAnimation(this._target);
+        };
+        StopAnimationAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "StopAnimationAction",
+                properties: [BABYLON.Action._GetTargetProperty(this._target)]
+            }, parent);
+        };
+        return StopAnimationAction;
+    })(BABYLON.Action);
+    BABYLON.StopAnimationAction = StopAnimationAction;
+    var DoNothingAction = (function (_super) {
+        __extends(DoNothingAction, _super);
+        function DoNothingAction(triggerOptions, condition) {
+            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
+            _super.call(this, triggerOptions, condition);
+        }
+        DoNothingAction.prototype.execute = function () {
+        };
+        DoNothingAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "DoNothingAction",
+                properties: []
+            }, parent);
+        };
+        return DoNothingAction;
+    })(BABYLON.Action);
+    BABYLON.DoNothingAction = DoNothingAction;
+    var CombineAction = (function (_super) {
+        __extends(CombineAction, _super);
+        function CombineAction(triggerOptions, children, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.children = children;
+        }
+        CombineAction.prototype._prepare = function () {
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._actionManager = this._actionManager;
+                this.children[index]._prepare();
+            }
+        };
+        CombineAction.prototype.execute = function (evt) {
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index].execute(evt);
+            }
+        };
+        CombineAction.prototype.serialize = function (parent) {
+            var serializationObject = _super.prototype._serialize.call(this, {
+                name: "CombineAction",
+                properties: [],
+                combine: []
+            }, parent);
+            for (var i = 0; i < this.children.length; i++) {
+                serializationObject.combine.push(this.children[i].serialize(null));
+            }
+            return serializationObject;
+        };
+        return CombineAction;
+    })(BABYLON.Action);
+    BABYLON.CombineAction = CombineAction;
+    var ExecuteCodeAction = (function (_super) {
+        __extends(ExecuteCodeAction, _super);
+        function ExecuteCodeAction(triggerOptions, func, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.func = func;
+        }
+        ExecuteCodeAction.prototype.execute = function (evt) {
+            this.func(evt);
+        };
+        return ExecuteCodeAction;
+    })(BABYLON.Action);
+    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
+    var SetParentAction = (function (_super) {
+        __extends(SetParentAction, _super);
+        function SetParentAction(triggerOptions, target, parent, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._target = target;
+            this._parent = parent;
+        }
+        SetParentAction.prototype._prepare = function () {
+        };
+        SetParentAction.prototype.execute = function () {
+            if (this._target.parent === this._parent) {
+                return;
+            }
+            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
+            invertParentWorldMatrix.invert();
+            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
+            this._target.parent = this._parent;
+        };
+        SetParentAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "SetParentAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    BABYLON.Action._GetTargetProperty(this._parent),
+                ]
+            }, parent);
+        };
+        return SetParentAction;
+    })(BABYLON.Action);
+    BABYLON.SetParentAction = SetParentAction;
+    var PlaySoundAction = (function (_super) {
+        __extends(PlaySoundAction, _super);
+        function PlaySoundAction(triggerOptions, sound, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._sound = sound;
+        }
+        PlaySoundAction.prototype._prepare = function () {
+        };
+        PlaySoundAction.prototype.execute = function () {
+            if (this._sound !== undefined)
+                this._sound.play();
+        };
+        PlaySoundAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "PlaySoundAction",
+                properties: [{ name: "sound", value: this._sound.name }]
+            }, parent);
+        };
+        return PlaySoundAction;
+    })(BABYLON.Action);
+    BABYLON.PlaySoundAction = PlaySoundAction;
+    var StopSoundAction = (function (_super) {
+        __extends(StopSoundAction, _super);
+        function StopSoundAction(triggerOptions, sound, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._sound = sound;
+        }
+        StopSoundAction.prototype._prepare = function () {
+        };
+        StopSoundAction.prototype.execute = function () {
+            if (this._sound !== undefined)
+                this._sound.stop();
+        };
+        StopSoundAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "StopSoundAction",
+                properties: [{ name: "sound", value: this._sound.name }]
+            }, parent);
+        };
+        return StopSoundAction;
+    })(BABYLON.Action);
+    BABYLON.StopSoundAction = StopSoundAction;
+})(BABYLON || (BABYLON = {}));

+ 77 - 78
src/Actions/babylon.interpolateValueAction.js

@@ -1,78 +1,77 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var InterpolateValueAction = (function (_super) {
-        __extends(InterpolateValueAction, _super);
-        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
-            if (duration === void 0) { duration = 1000; }
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this.duration = duration;
-            this.stopOtherAnimations = stopOtherAnimations;
-            this.onInterpolationDone = onInterpolationDone;
-            this._target = this._effectiveTarget = target;
-        }
-        InterpolateValueAction.prototype._prepare = function () {
-            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        InterpolateValueAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            var keys = [
-                {
-                    frame: 0,
-                    value: this._effectiveTarget[this._property]
-                }, {
-                    frame: 100,
-                    value: this.value
-                }
-            ];
-            var dataType;
-            if (typeof this.value === "number") {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
-            }
-            else if (this.value instanceof BABYLON.Color3) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
-            }
-            else if (this.value instanceof BABYLON.Vector3) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
-            }
-            else if (this.value instanceof BABYLON.Matrix) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
-            }
-            else if (this.value instanceof BABYLON.Quaternion) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
-            }
-            else {
-                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
-                return;
-            }
-            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
-            animation.setKeys(keys);
-            if (this.stopOtherAnimations) {
-                scene.stopAnimation(this._effectiveTarget);
-            }
-            scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
-        };
-        InterpolateValueAction.prototype.serialize = function (parent) {
-            return _super.prototype._serialize.call(this, {
-                name: "InterpolateValueAction",
-                properties: [
-                    BABYLON.Action._GetTargetProperty(this._target),
-                    { name: "propertyPath", value: this.propertyPath },
-                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
-                    { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
-                    { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
-                ]
-            }, parent);
-        };
-        return InterpolateValueAction;
-    }(BABYLON.Action));
-    BABYLON.InterpolateValueAction = InterpolateValueAction;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.interpolateValueAction.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var InterpolateValueAction = (function (_super) {
+        __extends(InterpolateValueAction, _super);
+        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
+            if (duration === void 0) { duration = 1000; }
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this.duration = duration;
+            this.stopOtherAnimations = stopOtherAnimations;
+            this.onInterpolationDone = onInterpolationDone;
+            this._target = this._effectiveTarget = target;
+        }
+        InterpolateValueAction.prototype._prepare = function () {
+            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        InterpolateValueAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            var keys = [
+                {
+                    frame: 0,
+                    value: this._effectiveTarget[this._property]
+                }, {
+                    frame: 100,
+                    value: this.value
+                }
+            ];
+            var dataType;
+            if (typeof this.value === "number") {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
+            }
+            else if (this.value instanceof BABYLON.Color3) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
+            }
+            else if (this.value instanceof BABYLON.Vector3) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
+            }
+            else if (this.value instanceof BABYLON.Matrix) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
+            }
+            else if (this.value instanceof BABYLON.Quaternion) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
+            }
+            else {
+                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
+                return;
+            }
+            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
+            animation.setKeys(keys);
+            if (this.stopOtherAnimations) {
+                scene.stopAnimation(this._effectiveTarget);
+            }
+            scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
+        };
+        InterpolateValueAction.prototype.serialize = function (parent) {
+            return _super.prototype._serialize.call(this, {
+                name: "InterpolateValueAction",
+                properties: [
+                    BABYLON.Action._GetTargetProperty(this._target),
+                    { name: "propertyPath", value: this.propertyPath },
+                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
+                    { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
+                    { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
+                ]
+            }, parent);
+        };
+        return InterpolateValueAction;
+    })(BABYLON.Action);
+    BABYLON.InterpolateValueAction = InterpolateValueAction;
+})(BABYLON || (BABYLON = {}));

+ 132 - 133
src/Animations/babylon.animatable.js

@@ -1,133 +1,132 @@
-var BABYLON;
-(function (BABYLON) {
-    var Animatable = (function () {
-        function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
-            if (fromFrame === void 0) { fromFrame = 0; }
-            if (toFrame === void 0) { toFrame = 100; }
-            if (loopAnimation === void 0) { loopAnimation = false; }
-            if (speedRatio === void 0) { speedRatio = 1.0; }
-            this.target = target;
-            this.fromFrame = fromFrame;
-            this.toFrame = toFrame;
-            this.loopAnimation = loopAnimation;
-            this.speedRatio = speedRatio;
-            this.onAnimationEnd = onAnimationEnd;
-            this._animations = new Array();
-            this._paused = false;
-            this.animationStarted = false;
-            if (animations) {
-                this.appendAnimations(target, animations);
-            }
-            this._scene = scene;
-            scene._activeAnimatables.push(this);
-        }
-        // Methods
-        Animatable.prototype.getAnimations = function () {
-            return this._animations;
-        };
-        Animatable.prototype.appendAnimations = function (target, animations) {
-            for (var index = 0; index < animations.length; index++) {
-                var animation = animations[index];
-                animation._target = target;
-                this._animations.push(animation);
-            }
-        };
-        Animatable.prototype.getAnimationByTargetProperty = function (property) {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                if (animations[index].targetProperty === property) {
-                    return animations[index];
-                }
-            }
-            return null;
-        };
-        Animatable.prototype.reset = function () {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].reset();
-            }
-            this._localDelayOffset = null;
-            this._pausedDelay = null;
-        };
-        Animatable.prototype.enableBlending = function (blendingSpeed) {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].enableBlending = true;
-                animations[index].blendingSpeed = blendingSpeed;
-            }
-        };
-        Animatable.prototype.disableBlending = function () {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].enableBlending = false;
-            }
-        };
-        Animatable.prototype.goToFrame = function (frame) {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].goToFrame(frame);
-            }
-        };
-        Animatable.prototype.pause = function () {
-            if (this._paused) {
-                return;
-            }
-            this._paused = true;
-        };
-        Animatable.prototype.restart = function () {
-            this._paused = false;
-        };
-        Animatable.prototype.stop = function () {
-            var index = this._scene._activeAnimatables.indexOf(this);
-            if (index > -1) {
-                this._scene._activeAnimatables.splice(index, 1);
-                var animations = this._animations;
-                for (var index = 0; index < animations.length; index++) {
-                    animations[index].reset();
-                }
-                if (this.onAnimationEnd) {
-                    this.onAnimationEnd();
-                }
-            }
-        };
-        Animatable.prototype._animate = function (delay) {
-            if (this._paused) {
-                this.animationStarted = false;
-                if (!this._pausedDelay) {
-                    this._pausedDelay = delay;
-                }
-                return true;
-            }
-            if (!this._localDelayOffset) {
-                this._localDelayOffset = delay;
-            }
-            else if (this._pausedDelay) {
-                this._localDelayOffset += delay - this._pausedDelay;
-                this._pausedDelay = null;
-            }
-            // Animating
-            var running = false;
-            var animations = this._animations;
-            var index;
-            for (index = 0; index < animations.length; index++) {
-                var animation = animations[index];
-                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
-                running = running || isRunning;
-            }
-            this.animationStarted = running;
-            if (!running) {
-                // Remove from active animatables
-                index = this._scene._activeAnimatables.indexOf(this);
-                this._scene._activeAnimatables.splice(index, 1);
-            }
-            if (!running && this.onAnimationEnd) {
-                this.onAnimationEnd();
-                this.onAnimationEnd = null;
-            }
-            return running;
-        };
-        return Animatable;
-    }());
-    BABYLON.Animatable = Animatable;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.animatable.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Animatable = (function () {
+        function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
+            if (fromFrame === void 0) { fromFrame = 0; }
+            if (toFrame === void 0) { toFrame = 100; }
+            if (loopAnimation === void 0) { loopAnimation = false; }
+            if (speedRatio === void 0) { speedRatio = 1.0; }
+            this.target = target;
+            this.fromFrame = fromFrame;
+            this.toFrame = toFrame;
+            this.loopAnimation = loopAnimation;
+            this.speedRatio = speedRatio;
+            this.onAnimationEnd = onAnimationEnd;
+            this._animations = new Array();
+            this._paused = false;
+            this.animationStarted = false;
+            if (animations) {
+                this.appendAnimations(target, animations);
+            }
+            this._scene = scene;
+            scene._activeAnimatables.push(this);
+        }
+        // Methods
+        Animatable.prototype.getAnimations = function () {
+            return this._animations;
+        };
+        Animatable.prototype.appendAnimations = function (target, animations) {
+            for (var index = 0; index < animations.length; index++) {
+                var animation = animations[index];
+                animation._target = target;
+                this._animations.push(animation);
+            }
+        };
+        Animatable.prototype.getAnimationByTargetProperty = function (property) {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                if (animations[index].targetProperty === property) {
+                    return animations[index];
+                }
+            }
+            return null;
+        };
+        Animatable.prototype.reset = function () {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].reset();
+            }
+            this._localDelayOffset = null;
+            this._pausedDelay = null;
+        };
+        Animatable.prototype.enableBlending = function (blendingSpeed) {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].enableBlending = true;
+                animations[index].blendingSpeed = blendingSpeed;
+            }
+        };
+        Animatable.prototype.disableBlending = function () {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].enableBlending = false;
+            }
+        };
+        Animatable.prototype.goToFrame = function (frame) {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].goToFrame(frame);
+            }
+        };
+        Animatable.prototype.pause = function () {
+            if (this._paused) {
+                return;
+            }
+            this._paused = true;
+        };
+        Animatable.prototype.restart = function () {
+            this._paused = false;
+        };
+        Animatable.prototype.stop = function () {
+            var index = this._scene._activeAnimatables.indexOf(this);
+            if (index > -1) {
+                this._scene._activeAnimatables.splice(index, 1);
+                var animations = this._animations;
+                for (var index = 0; index < animations.length; index++) {
+                    animations[index].reset();
+                }
+                if (this.onAnimationEnd) {
+                    this.onAnimationEnd();
+                }
+            }
+        };
+        Animatable.prototype._animate = function (delay) {
+            if (this._paused) {
+                this.animationStarted = false;
+                if (!this._pausedDelay) {
+                    this._pausedDelay = delay;
+                }
+                return true;
+            }
+            if (!this._localDelayOffset) {
+                this._localDelayOffset = delay;
+            }
+            else if (this._pausedDelay) {
+                this._localDelayOffset += delay - this._pausedDelay;
+                this._pausedDelay = null;
+            }
+            // Animating
+            var running = false;
+            var animations = this._animations;
+            var index;
+            for (index = 0; index < animations.length; index++) {
+                var animation = animations[index];
+                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
+                running = running || isRunning;
+            }
+            this.animationStarted = running;
+            if (!running) {
+                // Remove from active animatables
+                index = this._scene._activeAnimatables.indexOf(this);
+                this._scene._activeAnimatables.splice(index, 1);
+            }
+            if (!running && this.onAnimationEnd) {
+                this.onAnimationEnd();
+                this.onAnimationEnd = null;
+            }
+            return running;
+        };
+        return Animatable;
+    })();
+    BABYLON.Animatable = Animatable;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 741 - 742
src/Animations/babylon.animation.js


+ 249 - 250
src/Animations/babylon.easing.js

@@ -1,250 +1,249 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var EasingFunction = (function () {
-        function EasingFunction() {
-            // Properties
-            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
-        }
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEIN;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEOUT;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEINOUT;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        EasingFunction.prototype.setEasingMode = function (easingMode) {
-            var n = Math.min(Math.max(easingMode, 0), 2);
-            this._easingMode = n;
-        };
-        EasingFunction.prototype.getEasingMode = function () {
-            return this._easingMode;
-        };
-        EasingFunction.prototype.easeInCore = function (gradient) {
-            throw new Error('You must implement this method');
-        };
-        EasingFunction.prototype.ease = function (gradient) {
-            switch (this._easingMode) {
-                case EasingFunction.EASINGMODE_EASEIN:
-                    return this.easeInCore(gradient);
-                case EasingFunction.EASINGMODE_EASEOUT:
-                    return (1 - this.easeInCore(1 - gradient));
-            }
-            if (gradient >= 0.5) {
-                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
-            }
-            return (this.easeInCore(gradient * 2) * 0.5);
-        };
-        //Statics
-        EasingFunction._EASINGMODE_EASEIN = 0;
-        EasingFunction._EASINGMODE_EASEOUT = 1;
-        EasingFunction._EASINGMODE_EASEINOUT = 2;
-        return EasingFunction;
-    }());
-    BABYLON.EasingFunction = EasingFunction;
-    var CircleEase = (function (_super) {
-        __extends(CircleEase, _super);
-        function CircleEase() {
-            _super.apply(this, arguments);
-        }
-        CircleEase.prototype.easeInCore = function (gradient) {
-            gradient = Math.max(0, Math.min(1, gradient));
-            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
-        };
-        return CircleEase;
-    }(EasingFunction));
-    BABYLON.CircleEase = CircleEase;
-    var BackEase = (function (_super) {
-        __extends(BackEase, _super);
-        function BackEase(amplitude) {
-            if (amplitude === void 0) { amplitude = 1; }
-            _super.call(this);
-            this.amplitude = amplitude;
-        }
-        BackEase.prototype.easeInCore = function (gradient) {
-            var num = Math.max(0, this.amplitude);
-            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
-        };
-        return BackEase;
-    }(EasingFunction));
-    BABYLON.BackEase = BackEase;
-    var BounceEase = (function (_super) {
-        __extends(BounceEase, _super);
-        function BounceEase(bounces, bounciness) {
-            if (bounces === void 0) { bounces = 3; }
-            if (bounciness === void 0) { bounciness = 2; }
-            _super.call(this);
-            this.bounces = bounces;
-            this.bounciness = bounciness;
-        }
-        BounceEase.prototype.easeInCore = function (gradient) {
-            var y = Math.max(0.0, this.bounces);
-            var bounciness = this.bounciness;
-            if (bounciness <= 1.0) {
-                bounciness = 1.001;
-            }
-            var num9 = Math.pow(bounciness, y);
-            var num5 = 1.0 - bounciness;
-            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
-            var num15 = gradient * num4;
-            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
-            var num3 = Math.floor(num65);
-            var num13 = num3 + 1.0;
-            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
-            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
-            var num7 = (num8 + num12) * 0.5;
-            var num6 = gradient - num7;
-            var num2 = num7 - num8;
-            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
-        };
-        return BounceEase;
-    }(EasingFunction));
-    BABYLON.BounceEase = BounceEase;
-    var CubicEase = (function (_super) {
-        __extends(CubicEase, _super);
-        function CubicEase() {
-            _super.apply(this, arguments);
-        }
-        CubicEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient);
-        };
-        return CubicEase;
-    }(EasingFunction));
-    BABYLON.CubicEase = CubicEase;
-    var ElasticEase = (function (_super) {
-        __extends(ElasticEase, _super);
-        function ElasticEase(oscillations, springiness) {
-            if (oscillations === void 0) { oscillations = 3; }
-            if (springiness === void 0) { springiness = 3; }
-            _super.call(this);
-            this.oscillations = oscillations;
-            this.springiness = springiness;
-        }
-        ElasticEase.prototype.easeInCore = function (gradient) {
-            var num2;
-            var num3 = Math.max(0.0, this.oscillations);
-            var num = Math.max(0.0, this.springiness);
-            if (num == 0) {
-                num2 = gradient;
-            }
-            else {
-                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
-            }
-            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
-        };
-        return ElasticEase;
-    }(EasingFunction));
-    BABYLON.ElasticEase = ElasticEase;
-    var ExponentialEase = (function (_super) {
-        __extends(ExponentialEase, _super);
-        function ExponentialEase(exponent) {
-            if (exponent === void 0) { exponent = 2; }
-            _super.call(this);
-            this.exponent = exponent;
-        }
-        ExponentialEase.prototype.easeInCore = function (gradient) {
-            if (this.exponent <= 0) {
-                return gradient;
-            }
-            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
-        };
-        return ExponentialEase;
-    }(EasingFunction));
-    BABYLON.ExponentialEase = ExponentialEase;
-    var PowerEase = (function (_super) {
-        __extends(PowerEase, _super);
-        function PowerEase(power) {
-            if (power === void 0) { power = 2; }
-            _super.call(this);
-            this.power = power;
-        }
-        PowerEase.prototype.easeInCore = function (gradient) {
-            var y = Math.max(0.0, this.power);
-            return Math.pow(gradient, y);
-        };
-        return PowerEase;
-    }(EasingFunction));
-    BABYLON.PowerEase = PowerEase;
-    var QuadraticEase = (function (_super) {
-        __extends(QuadraticEase, _super);
-        function QuadraticEase() {
-            _super.apply(this, arguments);
-        }
-        QuadraticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient);
-        };
-        return QuadraticEase;
-    }(EasingFunction));
-    BABYLON.QuadraticEase = QuadraticEase;
-    var QuarticEase = (function (_super) {
-        __extends(QuarticEase, _super);
-        function QuarticEase() {
-            _super.apply(this, arguments);
-        }
-        QuarticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient * gradient);
-        };
-        return QuarticEase;
-    }(EasingFunction));
-    BABYLON.QuarticEase = QuarticEase;
-    var QuinticEase = (function (_super) {
-        __extends(QuinticEase, _super);
-        function QuinticEase() {
-            _super.apply(this, arguments);
-        }
-        QuinticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient * gradient * gradient);
-        };
-        return QuinticEase;
-    }(EasingFunction));
-    BABYLON.QuinticEase = QuinticEase;
-    var SineEase = (function (_super) {
-        __extends(SineEase, _super);
-        function SineEase() {
-            _super.apply(this, arguments);
-        }
-        SineEase.prototype.easeInCore = function (gradient) {
-            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
-        };
-        return SineEase;
-    }(EasingFunction));
-    BABYLON.SineEase = SineEase;
-    var BezierCurveEase = (function (_super) {
-        __extends(BezierCurveEase, _super);
-        function BezierCurveEase(x1, y1, x2, y2) {
-            if (x1 === void 0) { x1 = 0; }
-            if (y1 === void 0) { y1 = 0; }
-            if (x2 === void 0) { x2 = 1; }
-            if (y2 === void 0) { y2 = 1; }
-            _super.call(this);
-            this.x1 = x1;
-            this.y1 = y1;
-            this.x2 = x2;
-            this.y2 = y2;
-        }
-        BezierCurveEase.prototype.easeInCore = function (gradient) {
-            return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
-        };
-        return BezierCurveEase;
-    }(EasingFunction));
-    BABYLON.BezierCurveEase = BezierCurveEase;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.easing.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var EasingFunction = (function () {
+        function EasingFunction() {
+            // Properties
+            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
+        }
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEIN;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEOUT;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEINOUT;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        EasingFunction.prototype.setEasingMode = function (easingMode) {
+            var n = Math.min(Math.max(easingMode, 0), 2);
+            this._easingMode = n;
+        };
+        EasingFunction.prototype.getEasingMode = function () {
+            return this._easingMode;
+        };
+        EasingFunction.prototype.easeInCore = function (gradient) {
+            throw new Error('You must implement this method');
+        };
+        EasingFunction.prototype.ease = function (gradient) {
+            switch (this._easingMode) {
+                case EasingFunction.EASINGMODE_EASEIN:
+                    return this.easeInCore(gradient);
+                case EasingFunction.EASINGMODE_EASEOUT:
+                    return (1 - this.easeInCore(1 - gradient));
+            }
+            if (gradient >= 0.5) {
+                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
+            }
+            return (this.easeInCore(gradient * 2) * 0.5);
+        };
+        //Statics
+        EasingFunction._EASINGMODE_EASEIN = 0;
+        EasingFunction._EASINGMODE_EASEOUT = 1;
+        EasingFunction._EASINGMODE_EASEINOUT = 2;
+        return EasingFunction;
+    })();
+    BABYLON.EasingFunction = EasingFunction;
+    var CircleEase = (function (_super) {
+        __extends(CircleEase, _super);
+        function CircleEase() {
+            _super.apply(this, arguments);
+        }
+        CircleEase.prototype.easeInCore = function (gradient) {
+            gradient = Math.max(0, Math.min(1, gradient));
+            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
+        };
+        return CircleEase;
+    })(EasingFunction);
+    BABYLON.CircleEase = CircleEase;
+    var BackEase = (function (_super) {
+        __extends(BackEase, _super);
+        function BackEase(amplitude) {
+            if (amplitude === void 0) { amplitude = 1; }
+            _super.call(this);
+            this.amplitude = amplitude;
+        }
+        BackEase.prototype.easeInCore = function (gradient) {
+            var num = Math.max(0, this.amplitude);
+            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
+        };
+        return BackEase;
+    })(EasingFunction);
+    BABYLON.BackEase = BackEase;
+    var BounceEase = (function (_super) {
+        __extends(BounceEase, _super);
+        function BounceEase(bounces, bounciness) {
+            if (bounces === void 0) { bounces = 3; }
+            if (bounciness === void 0) { bounciness = 2; }
+            _super.call(this);
+            this.bounces = bounces;
+            this.bounciness = bounciness;
+        }
+        BounceEase.prototype.easeInCore = function (gradient) {
+            var y = Math.max(0.0, this.bounces);
+            var bounciness = this.bounciness;
+            if (bounciness <= 1.0) {
+                bounciness = 1.001;
+            }
+            var num9 = Math.pow(bounciness, y);
+            var num5 = 1.0 - bounciness;
+            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
+            var num15 = gradient * num4;
+            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
+            var num3 = Math.floor(num65);
+            var num13 = num3 + 1.0;
+            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
+            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
+            var num7 = (num8 + num12) * 0.5;
+            var num6 = gradient - num7;
+            var num2 = num7 - num8;
+            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
+        };
+        return BounceEase;
+    })(EasingFunction);
+    BABYLON.BounceEase = BounceEase;
+    var CubicEase = (function (_super) {
+        __extends(CubicEase, _super);
+        function CubicEase() {
+            _super.apply(this, arguments);
+        }
+        CubicEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient);
+        };
+        return CubicEase;
+    })(EasingFunction);
+    BABYLON.CubicEase = CubicEase;
+    var ElasticEase = (function (_super) {
+        __extends(ElasticEase, _super);
+        function ElasticEase(oscillations, springiness) {
+            if (oscillations === void 0) { oscillations = 3; }
+            if (springiness === void 0) { springiness = 3; }
+            _super.call(this);
+            this.oscillations = oscillations;
+            this.springiness = springiness;
+        }
+        ElasticEase.prototype.easeInCore = function (gradient) {
+            var num2;
+            var num3 = Math.max(0.0, this.oscillations);
+            var num = Math.max(0.0, this.springiness);
+            if (num == 0) {
+                num2 = gradient;
+            }
+            else {
+                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
+            }
+            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
+        };
+        return ElasticEase;
+    })(EasingFunction);
+    BABYLON.ElasticEase = ElasticEase;
+    var ExponentialEase = (function (_super) {
+        __extends(ExponentialEase, _super);
+        function ExponentialEase(exponent) {
+            if (exponent === void 0) { exponent = 2; }
+            _super.call(this);
+            this.exponent = exponent;
+        }
+        ExponentialEase.prototype.easeInCore = function (gradient) {
+            if (this.exponent <= 0) {
+                return gradient;
+            }
+            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
+        };
+        return ExponentialEase;
+    })(EasingFunction);
+    BABYLON.ExponentialEase = ExponentialEase;
+    var PowerEase = (function (_super) {
+        __extends(PowerEase, _super);
+        function PowerEase(power) {
+            if (power === void 0) { power = 2; }
+            _super.call(this);
+            this.power = power;
+        }
+        PowerEase.prototype.easeInCore = function (gradient) {
+            var y = Math.max(0.0, this.power);
+            return Math.pow(gradient, y);
+        };
+        return PowerEase;
+    })(EasingFunction);
+    BABYLON.PowerEase = PowerEase;
+    var QuadraticEase = (function (_super) {
+        __extends(QuadraticEase, _super);
+        function QuadraticEase() {
+            _super.apply(this, arguments);
+        }
+        QuadraticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient);
+        };
+        return QuadraticEase;
+    })(EasingFunction);
+    BABYLON.QuadraticEase = QuadraticEase;
+    var QuarticEase = (function (_super) {
+        __extends(QuarticEase, _super);
+        function QuarticEase() {
+            _super.apply(this, arguments);
+        }
+        QuarticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient * gradient);
+        };
+        return QuarticEase;
+    })(EasingFunction);
+    BABYLON.QuarticEase = QuarticEase;
+    var QuinticEase = (function (_super) {
+        __extends(QuinticEase, _super);
+        function QuinticEase() {
+            _super.apply(this, arguments);
+        }
+        QuinticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient * gradient * gradient);
+        };
+        return QuinticEase;
+    })(EasingFunction);
+    BABYLON.QuinticEase = QuinticEase;
+    var SineEase = (function (_super) {
+        __extends(SineEase, _super);
+        function SineEase() {
+            _super.apply(this, arguments);
+        }
+        SineEase.prototype.easeInCore = function (gradient) {
+            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
+        };
+        return SineEase;
+    })(EasingFunction);
+    BABYLON.SineEase = SineEase;
+    var BezierCurveEase = (function (_super) {
+        __extends(BezierCurveEase, _super);
+        function BezierCurveEase(x1, y1, x2, y2) {
+            if (x1 === void 0) { x1 = 0; }
+            if (y1 === void 0) { y1 = 0; }
+            if (x2 === void 0) { x2 = 1; }
+            if (y2 === void 0) { y2 = 1; }
+            _super.call(this);
+            this.x1 = x1;
+            this.y1 = y1;
+            this.x2 = x2;
+            this.y2 = y2;
+        }
+        BezierCurveEase.prototype.easeInCore = function (gradient) {
+            return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
+        };
+        return BezierCurveEase;
+    })(EasingFunction);
+    BABYLON.BezierCurveEase = BezierCurveEase;
+})(BABYLON || (BABYLON = {}));

+ 111 - 112
src/Audio/babylon.analyser.js

@@ -1,112 +1,111 @@
-var BABYLON;
-(function (BABYLON) {
-    var Analyser = (function () {
-        function Analyser(scene) {
-            this.SMOOTHING = 0.75;
-            this.FFT_SIZE = 512;
-            this.BARGRAPHAMPLITUDE = 256;
-            this.DEBUGCANVASPOS = { x: 20, y: 20 };
-            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
-            this._scene = scene;
-            this._audioEngine = BABYLON.Engine.audioEngine;
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
-                this._webAudioAnalyser.minDecibels = -140;
-                this._webAudioAnalyser.maxDecibels = 0;
-                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
-                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
-                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
-            }
-        }
-        Analyser.prototype.getFrequencyBinCount = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                return this._webAudioAnalyser.frequencyBinCount;
-            }
-            else {
-                return 0;
-            }
-        };
-        Analyser.prototype.getByteFrequencyData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
-            }
-            return this._byteFreqs;
-        };
-        Analyser.prototype.getByteTimeDomainData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
-            }
-            return this._byteTime;
-        };
-        Analyser.prototype.getFloatFrequencyData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
-            }
-            return this._floatFreqs;
-        };
-        Analyser.prototype.drawDebugCanvas = function () {
-            var _this = this;
-            if (this._audioEngine.canUseWebAudio) {
-                if (!this._debugCanvas) {
-                    this._debugCanvas = document.createElement("canvas");
-                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
-                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
-                    this._debugCanvas.style.position = "absolute";
-                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
-                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
-                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
-                    document.body.appendChild(this._debugCanvas);
-                    this._registerFunc = function () {
-                        _this.drawDebugCanvas();
-                    };
-                    this._scene.registerBeforeRender(this._registerFunc);
-                }
-                if (this._registerFunc) {
-                    var workingArray = this.getByteFrequencyData();
-                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
-                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
-                    // Draw the frequency domain chart.
-                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
-                        var value = workingArray[i];
-                        var percent = value / this.BARGRAPHAMPLITUDE;
-                        var height = this.DEBUGCANVASSIZE.height * percent;
-                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
-                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
-                        var hue = i / this.getFrequencyBinCount() * 360;
-                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
-                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
-                    }
-                }
-            }
-        };
-        Analyser.prototype.stopDebugCanvas = function () {
-            if (this._debugCanvas) {
-                this._scene.unregisterBeforeRender(this._registerFunc);
-                this._registerFunc = null;
-                document.body.removeChild(this._debugCanvas);
-                this._debugCanvas = null;
-                this._debugCanvasContext = null;
-            }
-        };
-        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
-            if (this._audioEngine.canUseWebAudio) {
-                inputAudioNode.connect(this._webAudioAnalyser);
-                this._webAudioAnalyser.connect(outputAudioNode);
-            }
-        };
-        Analyser.prototype.dispose = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.disconnect();
-            }
-        };
-        return Analyser;
-    }());
-    BABYLON.Analyser = Analyser;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.analyser.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Analyser = (function () {
+        function Analyser(scene) {
+            this.SMOOTHING = 0.75;
+            this.FFT_SIZE = 512;
+            this.BARGRAPHAMPLITUDE = 256;
+            this.DEBUGCANVASPOS = { x: 20, y: 20 };
+            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
+            this._scene = scene;
+            this._audioEngine = BABYLON.Engine.audioEngine;
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
+                this._webAudioAnalyser.minDecibels = -140;
+                this._webAudioAnalyser.maxDecibels = 0;
+                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
+                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
+                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
+            }
+        }
+        Analyser.prototype.getFrequencyBinCount = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                return this._webAudioAnalyser.frequencyBinCount;
+            }
+            else {
+                return 0;
+            }
+        };
+        Analyser.prototype.getByteFrequencyData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
+            }
+            return this._byteFreqs;
+        };
+        Analyser.prototype.getByteTimeDomainData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
+            }
+            return this._byteTime;
+        };
+        Analyser.prototype.getFloatFrequencyData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
+            }
+            return this._floatFreqs;
+        };
+        Analyser.prototype.drawDebugCanvas = function () {
+            var _this = this;
+            if (this._audioEngine.canUseWebAudio) {
+                if (!this._debugCanvas) {
+                    this._debugCanvas = document.createElement("canvas");
+                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
+                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
+                    this._debugCanvas.style.position = "absolute";
+                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
+                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
+                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
+                    document.body.appendChild(this._debugCanvas);
+                    this._registerFunc = function () {
+                        _this.drawDebugCanvas();
+                    };
+                    this._scene.registerBeforeRender(this._registerFunc);
+                }
+                if (this._registerFunc) {
+                    var workingArray = this.getByteFrequencyData();
+                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
+                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
+                    // Draw the frequency domain chart.
+                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
+                        var value = workingArray[i];
+                        var percent = value / this.BARGRAPHAMPLITUDE;
+                        var height = this.DEBUGCANVASSIZE.height * percent;
+                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
+                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
+                        var hue = i / this.getFrequencyBinCount() * 360;
+                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
+                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
+                    }
+                }
+            }
+        };
+        Analyser.prototype.stopDebugCanvas = function () {
+            if (this._debugCanvas) {
+                this._scene.unregisterBeforeRender(this._registerFunc);
+                this._registerFunc = null;
+                document.body.removeChild(this._debugCanvas);
+                this._debugCanvas = null;
+                this._debugCanvasContext = null;
+            }
+        };
+        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
+            if (this._audioEngine.canUseWebAudio) {
+                inputAudioNode.connect(this._webAudioAnalyser);
+                this._webAudioAnalyser.connect(outputAudioNode);
+            }
+        };
+        Analyser.prototype.dispose = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.disconnect();
+            }
+        };
+        return Analyser;
+    })();
+    BABYLON.Analyser = Analyser;
+})(BABYLON || (BABYLON = {}));

+ 106 - 107
src/Audio/babylon.audioEngine.js

@@ -1,107 +1,106 @@
-var BABYLON;
-(function (BABYLON) {
-    var AudioEngine = (function () {
-        function AudioEngine() {
-            this._audioContext = null;
-            this._audioContextInitialized = false;
-            this.canUseWebAudio = false;
-            this.WarnedWebAudioUnsupported = false;
-            this.unlocked = false;
-            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
-                window.AudioContext = window.AudioContext || window.webkitAudioContext;
-                this.canUseWebAudio = true;
-            }
-            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
-                this._unlockiOSaudio();
-            }
-            else {
-                this.unlocked = true;
-            }
-        }
-        Object.defineProperty(AudioEngine.prototype, "audioContext", {
-            get: function () {
-                if (!this._audioContextInitialized) {
-                    this._initializeAudioContext();
-                }
-                return this._audioContext;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        AudioEngine.prototype._unlockiOSaudio = function () {
-            var _this = this;
-            var unlockaudio = function () {
-                var buffer = _this.audioContext.createBuffer(1, 1, 22050);
-                var source = _this.audioContext.createBufferSource();
-                source.buffer = buffer;
-                source.connect(_this.audioContext.destination);
-                source.start(0);
-                setTimeout(function () {
-                    if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
-                        _this.unlocked = true;
-                        window.removeEventListener('touchend', unlockaudio, false);
-                        if (_this.onAudioUnlocked) {
-                            _this.onAudioUnlocked();
-                        }
-                    }
-                }, 0);
-            };
-            window.addEventListener('touchend', unlockaudio, false);
-        };
-        AudioEngine.prototype._initializeAudioContext = function () {
-            try {
-                if (this.canUseWebAudio) {
-                    this._audioContext = new AudioContext();
-                    // create a global volume gain node 
-                    this.masterGain = this._audioContext.createGain();
-                    this.masterGain.gain.value = 1;
-                    this.masterGain.connect(this._audioContext.destination);
-                    this._audioContextInitialized = true;
-                }
-            }
-            catch (e) {
-                this.canUseWebAudio = false;
-                BABYLON.Tools.Error("Web Audio: " + e.message);
-            }
-        };
-        AudioEngine.prototype.dispose = function () {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                if (this._connectedAnalyser) {
-                    this._connectedAnalyser.stopDebugCanvas();
-                    this._connectedAnalyser.dispose();
-                    this.masterGain.disconnect();
-                    this.masterGain.connect(this._audioContext.destination);
-                    this._connectedAnalyser = null;
-                }
-                this.masterGain.gain.value = 1;
-            }
-            this.WarnedWebAudioUnsupported = false;
-        };
-        AudioEngine.prototype.getGlobalVolume = function () {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                return this.masterGain.gain.value;
-            }
-            else {
-                return -1;
-            }
-        };
-        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                this.masterGain.gain.value = newVolume;
-            }
-        };
-        AudioEngine.prototype.connectToAnalyser = function (analyser) {
-            if (this._connectedAnalyser) {
-                this._connectedAnalyser.stopDebugCanvas();
-            }
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                this._connectedAnalyser = analyser;
-                this.masterGain.disconnect();
-                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
-            }
-        };
-        return AudioEngine;
-    }());
-    BABYLON.AudioEngine = AudioEngine;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.audioEngine.js.map
+var BABYLON;
+(function (BABYLON) {
+    var AudioEngine = (function () {
+        function AudioEngine() {
+            this._audioContext = null;
+            this._audioContextInitialized = false;
+            this.canUseWebAudio = false;
+            this.WarnedWebAudioUnsupported = false;
+            this.unlocked = false;
+            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
+                window.AudioContext = window.AudioContext || window.webkitAudioContext;
+                this.canUseWebAudio = true;
+            }
+            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
+                this._unlockiOSaudio();
+            }
+            else {
+                this.unlocked = true;
+            }
+        }
+        Object.defineProperty(AudioEngine.prototype, "audioContext", {
+            get: function () {
+                if (!this._audioContextInitialized) {
+                    this._initializeAudioContext();
+                }
+                return this._audioContext;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        AudioEngine.prototype._unlockiOSaudio = function () {
+            var _this = this;
+            var unlockaudio = function () {
+                var buffer = _this.audioContext.createBuffer(1, 1, 22050);
+                var source = _this.audioContext.createBufferSource();
+                source.buffer = buffer;
+                source.connect(_this.audioContext.destination);
+                source.start(0);
+                setTimeout(function () {
+                    if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
+                        _this.unlocked = true;
+                        window.removeEventListener('touchend', unlockaudio, false);
+                        if (_this.onAudioUnlocked) {
+                            _this.onAudioUnlocked();
+                        }
+                    }
+                }, 0);
+            };
+            window.addEventListener('touchend', unlockaudio, false);
+        };
+        AudioEngine.prototype._initializeAudioContext = function () {
+            try {
+                if (this.canUseWebAudio) {
+                    this._audioContext = new AudioContext();
+                    // create a global volume gain node 
+                    this.masterGain = this._audioContext.createGain();
+                    this.masterGain.gain.value = 1;
+                    this.masterGain.connect(this._audioContext.destination);
+                    this._audioContextInitialized = true;
+                }
+            }
+            catch (e) {
+                this.canUseWebAudio = false;
+                BABYLON.Tools.Error("Web Audio: " + e.message);
+            }
+        };
+        AudioEngine.prototype.dispose = function () {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                if (this._connectedAnalyser) {
+                    this._connectedAnalyser.stopDebugCanvas();
+                    this._connectedAnalyser.dispose();
+                    this.masterGain.disconnect();
+                    this.masterGain.connect(this._audioContext.destination);
+                    this._connectedAnalyser = null;
+                }
+                this.masterGain.gain.value = 1;
+            }
+            this.WarnedWebAudioUnsupported = false;
+        };
+        AudioEngine.prototype.getGlobalVolume = function () {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                return this.masterGain.gain.value;
+            }
+            else {
+                return -1;
+            }
+        };
+        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                this.masterGain.gain.value = newVolume;
+            }
+        };
+        AudioEngine.prototype.connectToAnalyser = function (analyser) {
+            if (this._connectedAnalyser) {
+                this._connectedAnalyser.stopDebugCanvas();
+            }
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                this._connectedAnalyser = analyser;
+                this.masterGain.disconnect();
+                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
+            }
+        };
+        return AudioEngine;
+    })();
+    BABYLON.AudioEngine = AudioEngine;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 560 - 561
src/Audio/babylon.sound.js


+ 101 - 102
src/Audio/babylon.soundtrack.js

@@ -1,102 +1,101 @@
-var BABYLON;
-(function (BABYLON) {
-    var SoundTrack = (function () {
-        function SoundTrack(scene, options) {
-            this.id = -1;
-            this._isMainTrack = false;
-            this._isInitialized = false;
-            this._scene = scene;
-            this.soundCollection = new Array();
-            this._options = options;
-            if (!this._isMainTrack) {
-                this._scene.soundTracks.push(this);
-                this.id = this._scene.soundTracks.length - 1;
-            }
-        }
-        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
-                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
-                if (this._options) {
-                    if (this._options.volume) {
-                        this._outputAudioNode.gain.value = this._options.volume;
-                    }
-                    if (this._options.mainTrack) {
-                        this._isMainTrack = this._options.mainTrack;
-                    }
-                }
-                this._isInitialized = true;
-            }
-        };
-        SoundTrack.prototype.dispose = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                if (this._connectedAnalyser) {
-                    this._connectedAnalyser.stopDebugCanvas();
-                }
-                while (this.soundCollection.length) {
-                    this.soundCollection[0].dispose();
-                }
-                if (this._outputAudioNode) {
-                    this._outputAudioNode.disconnect();
-                }
-                this._outputAudioNode = null;
-            }
-        };
-        SoundTrack.prototype.AddSound = function (sound) {
-            if (!this._isInitialized) {
-                this._initializeSoundTrackAudioGraph();
-            }
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
-            }
-            if (sound.soundTrackId) {
-                if (sound.soundTrackId === -1) {
-                    this._scene.mainSoundTrack.RemoveSound(sound);
-                }
-                else {
-                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
-                }
-            }
-            this.soundCollection.push(sound);
-            sound.soundTrackId = this.id;
-        };
-        SoundTrack.prototype.RemoveSound = function (sound) {
-            var index = this.soundCollection.indexOf(sound);
-            if (index !== -1) {
-                this.soundCollection.splice(index, 1);
-            }
-        };
-        SoundTrack.prototype.setVolume = function (newVolume) {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode.gain.value = newVolume;
-            }
-        };
-        SoundTrack.prototype.switchPanningModelToHRTF = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                for (var i = 0; i < this.soundCollection.length; i++) {
-                    this.soundCollection[i].switchPanningModelToHRTF();
-                }
-            }
-        };
-        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                for (var i = 0; i < this.soundCollection.length; i++) {
-                    this.soundCollection[i].switchPanningModelToEqualPower();
-                }
-            }
-        };
-        SoundTrack.prototype.connectToAnalyser = function (analyser) {
-            if (this._connectedAnalyser) {
-                this._connectedAnalyser.stopDebugCanvas();
-            }
-            this._connectedAnalyser = analyser;
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode.disconnect();
-                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
-            }
-        };
-        return SoundTrack;
-    }());
-    BABYLON.SoundTrack = SoundTrack;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.soundtrack.js.map
+var BABYLON;
+(function (BABYLON) {
+    var SoundTrack = (function () {
+        function SoundTrack(scene, options) {
+            this.id = -1;
+            this._isMainTrack = false;
+            this._isInitialized = false;
+            this._scene = scene;
+            this.soundCollection = new Array();
+            this._options = options;
+            if (!this._isMainTrack) {
+                this._scene.soundTracks.push(this);
+                this.id = this._scene.soundTracks.length - 1;
+            }
+        }
+        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
+                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
+                if (this._options) {
+                    if (this._options.volume) {
+                        this._outputAudioNode.gain.value = this._options.volume;
+                    }
+                    if (this._options.mainTrack) {
+                        this._isMainTrack = this._options.mainTrack;
+                    }
+                }
+                this._isInitialized = true;
+            }
+        };
+        SoundTrack.prototype.dispose = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                if (this._connectedAnalyser) {
+                    this._connectedAnalyser.stopDebugCanvas();
+                }
+                while (this.soundCollection.length) {
+                    this.soundCollection[0].dispose();
+                }
+                if (this._outputAudioNode) {
+                    this._outputAudioNode.disconnect();
+                }
+                this._outputAudioNode = null;
+            }
+        };
+        SoundTrack.prototype.AddSound = function (sound) {
+            if (!this._isInitialized) {
+                this._initializeSoundTrackAudioGraph();
+            }
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
+            }
+            if (sound.soundTrackId) {
+                if (sound.soundTrackId === -1) {
+                    this._scene.mainSoundTrack.RemoveSound(sound);
+                }
+                else {
+                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
+                }
+            }
+            this.soundCollection.push(sound);
+            sound.soundTrackId = this.id;
+        };
+        SoundTrack.prototype.RemoveSound = function (sound) {
+            var index = this.soundCollection.indexOf(sound);
+            if (index !== -1) {
+                this.soundCollection.splice(index, 1);
+            }
+        };
+        SoundTrack.prototype.setVolume = function (newVolume) {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode.gain.value = newVolume;
+            }
+        };
+        SoundTrack.prototype.switchPanningModelToHRTF = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                for (var i = 0; i < this.soundCollection.length; i++) {
+                    this.soundCollection[i].switchPanningModelToHRTF();
+                }
+            }
+        };
+        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                for (var i = 0; i < this.soundCollection.length; i++) {
+                    this.soundCollection[i].switchPanningModelToEqualPower();
+                }
+            }
+        };
+        SoundTrack.prototype.connectToAnalyser = function (analyser) {
+            if (this._connectedAnalyser) {
+                this._connectedAnalyser.stopDebugCanvas();
+            }
+            this._connectedAnalyser = analyser;
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode.disconnect();
+                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
+            }
+        };
+        return SoundTrack;
+    })();
+    BABYLON.SoundTrack = SoundTrack;
+})(BABYLON || (BABYLON = {}));

+ 141 - 142
src/Bones/babylon.bone.js

@@ -1,142 +1,141 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Bone = (function (_super) {
-        __extends(Bone, _super);
-        function Bone(name, skeleton, parentBone, matrix, restPose) {
-            _super.call(this, name, skeleton.getScene());
-            this.name = name;
-            this.children = new Array();
-            this.animations = new Array();
-            this._worldTransform = new BABYLON.Matrix();
-            this._absoluteTransform = new BABYLON.Matrix();
-            this._invertedAbsoluteTransform = new BABYLON.Matrix();
-            this._skeleton = skeleton;
-            this._matrix = matrix;
-            this._baseMatrix = matrix;
-            this._restPose = restPose ? restPose : matrix.clone();
-            skeleton.bones.push(this);
-            if (parentBone) {
-                this._parent = parentBone;
-                parentBone.children.push(this);
-            }
-            else {
-                this._parent = null;
-            }
-            this._updateDifferenceMatrix();
-        }
-        // Members
-        Bone.prototype.getParent = function () {
-            return this._parent;
-        };
-        Bone.prototype.getLocalMatrix = function () {
-            return this._matrix;
-        };
-        Bone.prototype.getBaseMatrix = function () {
-            return this._baseMatrix;
-        };
-        Bone.prototype.getRestPose = function () {
-            return this._restPose;
-        };
-        Bone.prototype.returnToRest = function () {
-            this.updateMatrix(this._restPose.clone());
-        };
-        Bone.prototype.getWorldMatrix = function () {
-            return this._worldTransform;
-        };
-        Bone.prototype.getInvertedAbsoluteTransform = function () {
-            return this._invertedAbsoluteTransform;
-        };
-        Bone.prototype.getAbsoluteTransform = function () {
-            return this._absoluteTransform;
-        };
-        // Methods
-        Bone.prototype.updateMatrix = function (matrix) {
-            this._baseMatrix = matrix.clone();
-            this._matrix = matrix.clone();
-            this._skeleton._markAsDirty();
-            this._updateDifferenceMatrix();
-        };
-        Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
-            if (!rootMatrix) {
-                rootMatrix = this._baseMatrix;
-            }
-            if (this._parent) {
-                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
-            }
-            else {
-                this._absoluteTransform.copyFrom(rootMatrix);
-            }
-            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index]._updateDifferenceMatrix();
-            }
-        };
-        Bone.prototype.markAsDirty = function () {
-            this._currentRenderId++;
-            this._skeleton._markAsDirty();
-        };
-        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
-            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
-            if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
-            // all animation may be coming from a library skeleton, so may need to create animation
-            if (this.animations.length === 0) {
-                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
-                this.animations[0].setKeys([]);
-            }
-            // get animation info / verify there is such a range from the source bone
-            var sourceRange = source.animations[0].getRange(rangeName);
-            if (!sourceRange) {
-                return false;
-            }
-            var from = sourceRange.from;
-            var to = sourceRange.to;
-            var sourceKeys = source.animations[0].getKeys();
-            // rescaling prep
-            var sourceBoneLength = source.length;
-            var sourceParent = source.getParent();
-            var parent = this.getParent();
-            var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
-            var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
-            var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
-            var destKeys = this.animations[0].getKeys();
-            // loop vars declaration
-            var orig;
-            var origTranslation;
-            var mat;
-            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
-                orig = sourceKeys[key];
-                if (orig.frame >= from && orig.frame <= to) {
-                    if (rescaleAsRequired) {
-                        mat = orig.value.clone();
-                        // scale based on parent ratio, when bone has parent
-                        if (parentScalingReqd) {
-                            origTranslation = mat.getTranslation();
-                            mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
-                        }
-                        else if (dimensionsScalingReqd) {
-                            origTranslation = mat.getTranslation();
-                            mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
-                        }
-                        else {
-                            mat = orig.value;
-                        }
-                    }
-                    else {
-                        mat = orig.value;
-                    }
-                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
-                }
-            }
-            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
-            return true;
-        };
-        return Bone;
-    }(BABYLON.Node));
-    BABYLON.Bone = Bone;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.bone.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Bone = (function (_super) {
+        __extends(Bone, _super);
+        function Bone(name, skeleton, parentBone, matrix, restPose) {
+            _super.call(this, name, skeleton.getScene());
+            this.name = name;
+            this.children = new Array();
+            this.animations = new Array();
+            this._worldTransform = new BABYLON.Matrix();
+            this._absoluteTransform = new BABYLON.Matrix();
+            this._invertedAbsoluteTransform = new BABYLON.Matrix();
+            this._skeleton = skeleton;
+            this._matrix = matrix;
+            this._baseMatrix = matrix;
+            this._restPose = restPose ? restPose : matrix.clone();
+            skeleton.bones.push(this);
+            if (parentBone) {
+                this._parent = parentBone;
+                parentBone.children.push(this);
+            }
+            else {
+                this._parent = null;
+            }
+            this._updateDifferenceMatrix();
+        }
+        // Members
+        Bone.prototype.getParent = function () {
+            return this._parent;
+        };
+        Bone.prototype.getLocalMatrix = function () {
+            return this._matrix;
+        };
+        Bone.prototype.getBaseMatrix = function () {
+            return this._baseMatrix;
+        };
+        Bone.prototype.getRestPose = function () {
+            return this._restPose;
+        };
+        Bone.prototype.returnToRest = function () {
+            this.updateMatrix(this._restPose.clone());
+        };
+        Bone.prototype.getWorldMatrix = function () {
+            return this._worldTransform;
+        };
+        Bone.prototype.getInvertedAbsoluteTransform = function () {
+            return this._invertedAbsoluteTransform;
+        };
+        Bone.prototype.getAbsoluteTransform = function () {
+            return this._absoluteTransform;
+        };
+        // Methods
+        Bone.prototype.updateMatrix = function (matrix) {
+            this._baseMatrix = matrix.clone();
+            this._matrix = matrix.clone();
+            this._skeleton._markAsDirty();
+            this._updateDifferenceMatrix();
+        };
+        Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
+            if (!rootMatrix) {
+                rootMatrix = this._baseMatrix;
+            }
+            if (this._parent) {
+                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
+            }
+            else {
+                this._absoluteTransform.copyFrom(rootMatrix);
+            }
+            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._updateDifferenceMatrix();
+            }
+        };
+        Bone.prototype.markAsDirty = function () {
+            this._currentRenderId++;
+            this._skeleton._markAsDirty();
+        };
+        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
+            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
+            if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
+            // all animation may be coming from a library skeleton, so may need to create animation
+            if (this.animations.length === 0) {
+                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
+                this.animations[0].setKeys([]);
+            }
+            // get animation info / verify there is such a range from the source bone
+            var sourceRange = source.animations[0].getRange(rangeName);
+            if (!sourceRange) {
+                return false;
+            }
+            var from = sourceRange.from;
+            var to = sourceRange.to;
+            var sourceKeys = source.animations[0].getKeys();
+            // rescaling prep
+            var sourceBoneLength = source.length;
+            var sourceParent = source.getParent();
+            var parent = this.getParent();
+            var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
+            var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
+            var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
+            var destKeys = this.animations[0].getKeys();
+            // loop vars declaration
+            var orig;
+            var origTranslation;
+            var mat;
+            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
+                orig = sourceKeys[key];
+                if (orig.frame >= from && orig.frame <= to) {
+                    if (rescaleAsRequired) {
+                        mat = orig.value.clone();
+                        // scale based on parent ratio, when bone has parent
+                        if (parentScalingReqd) {
+                            origTranslation = mat.getTranslation();
+                            mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
+                        }
+                        else if (dimensionsScalingReqd) {
+                            origTranslation = mat.getTranslation();
+                            mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
+                        }
+                        else {
+                            mat = orig.value;
+                        }
+                    }
+                    else {
+                        mat = orig.value;
+                    }
+                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
+                }
+            }
+            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
+            return true;
+        };
+        return Bone;
+    })(BABYLON.Node);
+    BABYLON.Bone = Bone;
+})(BABYLON || (BABYLON = {}));

+ 71 - 72
src/Cameras/Inputs/babylon.arcrotatecamera.input.gamepad.js

@@ -1,72 +1,71 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var ArcRotateCameraGamepadInput = (function () {
-        function ArcRotateCameraGamepadInput() {
-            this.gamepadRotationSensibility = 80;
-            this.gamepadMoveSensibility = 40;
-        }
-        ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
-        };
-        ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
-            if (this._gamepads) {
-                this._gamepads.dispose();
-            }
-            this.gamepad = null;
-        };
-        ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
-            if (this.gamepad) {
-                var camera = this.camera;
-                var RSValues = this.gamepad.rightStick;
-                if (RSValues.x != 0) {
-                    var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
-                    if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
-                        camera.inertialAlphaOffset += normalizedRX;
-                    }
-                }
-                if (RSValues.y != 0) {
-                    var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
-                    if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
-                        camera.inertialBetaOffset += normalizedRY;
-                    }
-                }
-                var LSValues = this.gamepad.leftStick;
-                if (LSValues.y != 0) {
-                    var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
-                    if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
-                        this.camera.inertialRadiusOffset -= normalizedLY;
-                    }
-                }
-            }
-        };
-        ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
-            // Only the first gamepad can control the camera
-            if (gamepad.index === 0) {
-                this.gamepad = gamepad;
-            }
-        };
-        ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
-            return "ArcRotateCameraGamepadInput";
-        };
-        ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
-            return "gamepad";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
-        return ArcRotateCameraGamepadInput;
-    }());
-    BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
-    BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var ArcRotateCameraGamepadInput = (function () {
+        function ArcRotateCameraGamepadInput() {
+            this.gamepadRotationSensibility = 80;
+            this.gamepadMoveSensibility = 40;
+        }
+        ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
+        };
+        ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
+            if (this._gamepads) {
+                this._gamepads.dispose();
+            }
+            this.gamepad = null;
+        };
+        ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
+            if (this.gamepad) {
+                var camera = this.camera;
+                var RSValues = this.gamepad.rightStick;
+                if (RSValues.x != 0) {
+                    var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
+                    if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
+                        camera.inertialAlphaOffset += normalizedRX;
+                    }
+                }
+                if (RSValues.y != 0) {
+                    var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
+                    if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
+                        camera.inertialBetaOffset += normalizedRY;
+                    }
+                }
+                var LSValues = this.gamepad.leftStick;
+                if (LSValues.y != 0) {
+                    var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
+                    if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
+                        this.camera.inertialRadiusOffset -= normalizedLY;
+                    }
+                }
+            }
+        };
+        ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
+            // Only the first gamepad can control the camera
+            if (gamepad.index === 0) {
+                this.gamepad = gamepad;
+            }
+        };
+        ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
+            return "ArcRotateCameraGamepadInput";
+        };
+        ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
+            return "gamepad";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
+        return ArcRotateCameraGamepadInput;
+    })();
+    BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
+    BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
+})(BABYLON || (BABYLON = {}));

+ 113 - 114
src/Cameras/Inputs/babylon.arcrotatecamera.input.keyboard.js

@@ -1,114 +1,113 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var ArcRotateCameraKeyboardMoveInput = (function () {
-        function ArcRotateCameraKeyboardMoveInput() {
-            this._keys = [];
-            this.keysUp = [38];
-            this.keysDown = [40];
-            this.keysLeft = [37];
-            this.keysRight = [39];
-        }
-        ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            this._onKeyDown = function (evt) {
-                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                    var index = _this._keys.indexOf(evt.keyCode);
-                    if (index === -1) {
-                        _this._keys.push(evt.keyCode);
-                    }
-                    if (evt.preventDefault) {
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                }
-            };
-            this._onKeyUp = function (evt) {
-                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                    var index = _this._keys.indexOf(evt.keyCode);
-                    if (index >= 0) {
-                        _this._keys.splice(index, 1);
-                    }
-                    if (evt.preventDefault) {
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                }
-            };
-            this._onLostFocus = function () {
-                _this._keys = [];
-            };
-            BABYLON.Tools.RegisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        };
-        ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
-            BABYLON.Tools.UnregisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-            this._keys = [];
-            this._onKeyDown = null;
-            this._onKeyUp = null;
-            this._onLostFocus = null;
-        };
-        ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
-            if (this._onKeyDown) {
-                var camera = this.camera;
-                for (var index = 0; index < this._keys.length; index++) {
-                    var keyCode = this._keys[index];
-                    if (this.keysLeft.indexOf(keyCode) !== -1) {
-                        camera.inertialAlphaOffset -= 0.01;
-                    }
-                    else if (this.keysUp.indexOf(keyCode) !== -1) {
-                        camera.inertialBetaOffset -= 0.01;
-                    }
-                    else if (this.keysRight.indexOf(keyCode) !== -1) {
-                        camera.inertialAlphaOffset += 0.01;
-                    }
-                    else if (this.keysDown.indexOf(keyCode) !== -1) {
-                        camera.inertialBetaOffset += 0.01;
-                    }
-                }
-            }
-        };
-        ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
-            return "ArcRotateCameraKeyboardMoveInput";
-        };
-        ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
-            return "keyboard";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
-        return ArcRotateCameraKeyboardMoveInput;
-    }());
-    BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
-    BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var ArcRotateCameraKeyboardMoveInput = (function () {
+        function ArcRotateCameraKeyboardMoveInput() {
+            this._keys = [];
+            this.keysUp = [38];
+            this.keysDown = [40];
+            this.keysLeft = [37];
+            this.keysRight = [39];
+        }
+        ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            this._onKeyDown = function (evt) {
+                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                    var index = _this._keys.indexOf(evt.keyCode);
+                    if (index === -1) {
+                        _this._keys.push(evt.keyCode);
+                    }
+                    if (evt.preventDefault) {
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                }
+            };
+            this._onKeyUp = function (evt) {
+                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                    var index = _this._keys.indexOf(evt.keyCode);
+                    if (index >= 0) {
+                        _this._keys.splice(index, 1);
+                    }
+                    if (evt.preventDefault) {
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                }
+            };
+            this._onLostFocus = function () {
+                _this._keys = [];
+            };
+            BABYLON.Tools.RegisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+        };
+        ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
+            BABYLON.Tools.UnregisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+            this._keys = [];
+            this._onKeyDown = null;
+            this._onKeyUp = null;
+            this._onLostFocus = null;
+        };
+        ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
+            if (this._onKeyDown) {
+                var camera = this.camera;
+                for (var index = 0; index < this._keys.length; index++) {
+                    var keyCode = this._keys[index];
+                    if (this.keysLeft.indexOf(keyCode) !== -1) {
+                        camera.inertialAlphaOffset -= 0.01;
+                    }
+                    else if (this.keysUp.indexOf(keyCode) !== -1) {
+                        camera.inertialBetaOffset -= 0.01;
+                    }
+                    else if (this.keysRight.indexOf(keyCode) !== -1) {
+                        camera.inertialAlphaOffset += 0.01;
+                    }
+                    else if (this.keysDown.indexOf(keyCode) !== -1) {
+                        camera.inertialBetaOffset += 0.01;
+                    }
+                }
+            }
+        };
+        ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
+            return "ArcRotateCameraKeyboardMoveInput";
+        };
+        ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
+            return "keyboard";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
+        return ArcRotateCameraKeyboardMoveInput;
+    })();
+    BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
+    BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
+})(BABYLON || (BABYLON = {}));

+ 57 - 58
src/Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.js

@@ -1,58 +1,57 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var ArcRotateCameraMouseWheelInput = (function () {
-        function ArcRotateCameraMouseWheelInput() {
-            this.wheelPrecision = 3.0;
-        }
-        ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            this._wheel = function (p, s) {
-                //sanity check - this should be a PointerWheel event.
-                if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
-                    return;
-                var event = p.event;
-                var delta = 0;
-                if (event.wheelDelta) {
-                    delta = event.wheelDelta / (_this.wheelPrecision * 40);
-                }
-                else if (event.detail) {
-                    delta = -event.detail / _this.wheelPrecision;
-                }
-                if (delta)
-                    _this.camera.inertialRadiusOffset += delta;
-                if (event.preventDefault) {
-                    if (!noPreventDefault) {
-                        event.preventDefault();
-                    }
-                }
-            };
-            this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
-        };
-        ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
-            if (this._observer && element) {
-                this.camera.getScene().onPointerObservable.remove(this._observer);
-                this._observer = null;
-                this._wheel = null;
-            }
-        };
-        ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
-            return "ArcRotateCameraMouseWheelInput";
-        };
-        ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
-            return "mousewheel";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
-        return ArcRotateCameraMouseWheelInput;
-    }());
-    BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
-    BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var ArcRotateCameraMouseWheelInput = (function () {
+        function ArcRotateCameraMouseWheelInput() {
+            this.wheelPrecision = 3.0;
+        }
+        ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            this._wheel = function (p, s) {
+                //sanity check - this should be a PointerWheel event.
+                if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
+                    return;
+                var event = p.event;
+                var delta = 0;
+                if (event.wheelDelta) {
+                    delta = event.wheelDelta / (_this.wheelPrecision * 40);
+                }
+                else if (event.detail) {
+                    delta = -event.detail / _this.wheelPrecision;
+                }
+                if (delta)
+                    _this.camera.inertialRadiusOffset += delta;
+                if (event.preventDefault) {
+                    if (!noPreventDefault) {
+                        event.preventDefault();
+                    }
+                }
+            };
+            this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
+        };
+        ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
+            if (this._observer && element) {
+                this.camera.getScene().onPointerObservable.remove(this._observer);
+                this._observer = null;
+                this._wheel = null;
+            }
+        };
+        ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
+            return "ArcRotateCameraMouseWheelInput";
+        };
+        ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
+            return "mousewheel";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
+        return ArcRotateCameraMouseWheelInput;
+    })();
+    BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
+    BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
+})(BABYLON || (BABYLON = {}));

+ 219 - 220
src/Cameras/Inputs/babylon.arcrotatecamera.input.pointers.js

@@ -1,220 +1,219 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var eventPrefix = BABYLON.Tools.GetPointerPrefix();
-    var ArcRotateCameraPointersInput = (function () {
-        function ArcRotateCameraPointersInput() {
-            this.angularSensibilityX = 1000.0;
-            this.angularSensibilityY = 1000.0;
-            this.pinchPrecision = 6.0;
-            this.panningSensibility = 50.0;
-            this._isRightClick = false;
-            this._isCtrlPushed = false;
-            this.pinchInwards = true;
-        }
-        ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            var engine = this.camera.getEngine();
-            var cacheSoloPointer; // cache pointer object for better perf on camera rotation
-            var pointA, pointB;
-            var previousPinchDistance = 0;
-            this._pointerInput = function (p, s) {
-                var evt = p.event;
-                if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
-                    try {
-                        evt.srcElement.setPointerCapture(evt.pointerId);
-                    }
-                    catch (e) {
-                    }
-                    // Manage panning with right click
-                    _this._isRightClick = evt.button === 2;
-                    // manage pointers
-                    cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
-                    if (pointA === undefined) {
-                        pointA = cacheSoloPointer;
-                    }
-                    else if (pointB === undefined) {
-                        pointB = cacheSoloPointer;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                }
-                else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
-                    try {
-                        evt.srcElement.releasePointerCapture(evt.pointerId);
-                    }
-                    catch (e) {
-                    }
-                    cacheSoloPointer = null;
-                    previousPinchDistance = 0;
-                    //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, 
-                    //but emptying completly pointers collection is required to fix a bug on iPhone : 
-                    //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers  
-                    //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
-                    pointA = pointB = undefined;
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                }
-                else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    // One button down
-                    if (pointA && pointB === undefined) {
-                        if (_this.panningSensibility !== 0 &&
-                            ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
-                                (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
-                            _this.camera
-                                .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
-                            _this.camera
-                                .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
-                        }
-                        else {
-                            var offsetX = evt.clientX - cacheSoloPointer.x;
-                            var offsetY = evt.clientY - cacheSoloPointer.y;
-                            _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
-                            _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
-                        }
-                        cacheSoloPointer.x = evt.clientX;
-                        cacheSoloPointer.y = evt.clientY;
-                    }
-                    else if (pointA && pointB) {
-                        //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
-                        var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
-                        ed.x = evt.clientX;
-                        ed.y = evt.clientY;
-                        var direction = _this.pinchInwards ? 1 : -1;
-                        var distX = pointA.x - pointB.x;
-                        var distY = pointA.y - pointB.y;
-                        var pinchSquaredDistance = (distX * distX) + (distY * distY);
-                        if (previousPinchDistance === 0) {
-                            previousPinchDistance = pinchSquaredDistance;
-                            return;
-                        }
-                        if (pinchSquaredDistance !== previousPinchDistance) {
-                            _this.camera
-                                .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
-                                (_this.pinchPrecision *
-                                    ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
-                                    direction);
-                            previousPinchDistance = pinchSquaredDistance;
-                        }
-                    }
-                }
-            };
-            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
-            this._onContextMenu = function (evt) {
-                evt.preventDefault();
-            };
-            if (!this.camera._useCtrlForPanning) {
-                element.addEventListener("contextmenu", this._onContextMenu, false);
-            }
-            this._onLostFocus = function () {
-                //this._keys = [];
-                pointA = pointB = undefined;
-                previousPinchDistance = 0;
-                cacheSoloPointer = null;
-            };
-            this._onKeyDown = function (evt) {
-                _this._isCtrlPushed = evt.ctrlKey;
-            };
-            this._onKeyUp = function (evt) {
-                _this._isCtrlPushed = evt.ctrlKey;
-            };
-            this._onMouseMove = function (evt) {
-                if (!engine.isPointerLock) {
-                    return;
-                }
-                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
-                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
-                _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
-                _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
-                if (!noPreventDefault) {
-                    evt.preventDefault();
-                }
-            };
-            this._onGestureStart = function (e) {
-                if (window.MSGesture === undefined) {
-                    return;
-                }
-                if (!_this._MSGestureHandler) {
-                    _this._MSGestureHandler = new MSGesture();
-                    _this._MSGestureHandler.target = element;
-                }
-                _this._MSGestureHandler.addPointer(e.pointerId);
-            };
-            this._onGesture = function (e) {
-                _this.camera.radius *= e.scale;
-                if (e.preventDefault) {
-                    if (!noPreventDefault) {
-                        e.stopPropagation();
-                        e.preventDefault();
-                    }
-                }
-            };
-            element.addEventListener("mousemove", this._onMouseMove, false);
-            element.addEventListener("MSPointerDown", this._onGestureStart, false);
-            element.addEventListener("MSGestureChange", this._onGesture, false);
-            BABYLON.Tools.RegisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        };
-        ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
-            if (element && this._observer) {
-                this.camera.getScene().onPointerObservable.remove(this._observer);
-                this._observer = null;
-                element.removeEventListener("contextmenu", this._onContextMenu);
-                element.removeEventListener("mousemove", this._onMouseMove);
-                element.removeEventListener("MSPointerDown", this._onGestureStart);
-                element.removeEventListener("MSGestureChange", this._onGesture);
-                this._isRightClick = false;
-                this._isCtrlPushed = false;
-                this.pinchInwards = true;
-                this._onKeyDown = null;
-                this._onKeyUp = null;
-                this._onMouseMove = null;
-                this._onGestureStart = null;
-                this._onGesture = null;
-                this._MSGestureHandler = null;
-                this._onLostFocus = null;
-                this._onContextMenu = null;
-            }
-            BABYLON.Tools.UnregisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        };
-        ArcRotateCameraPointersInput.prototype.getTypeName = function () {
-            return "ArcRotateCameraPointersInput";
-        };
-        ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
-            return "pointers";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
-        return ArcRotateCameraPointersInput;
-    }());
-    BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
-    BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var eventPrefix = BABYLON.Tools.GetPointerPrefix();
+    var ArcRotateCameraPointersInput = (function () {
+        function ArcRotateCameraPointersInput() {
+            this.angularSensibilityX = 1000.0;
+            this.angularSensibilityY = 1000.0;
+            this.pinchPrecision = 6.0;
+            this.panningSensibility = 50.0;
+            this._isRightClick = false;
+            this._isCtrlPushed = false;
+            this.pinchInwards = true;
+        }
+        ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            var engine = this.camera.getEngine();
+            var cacheSoloPointer; // cache pointer object for better perf on camera rotation
+            var pointA, pointB;
+            var previousPinchDistance = 0;
+            this._pointerInput = function (p, s) {
+                var evt = p.event;
+                if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
+                    try {
+                        evt.srcElement.setPointerCapture(evt.pointerId);
+                    }
+                    catch (e) {
+                    }
+                    // Manage panning with right click
+                    _this._isRightClick = evt.button === 2;
+                    // manage pointers
+                    cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
+                    if (pointA === undefined) {
+                        pointA = cacheSoloPointer;
+                    }
+                    else if (pointB === undefined) {
+                        pointB = cacheSoloPointer;
+                    }
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                }
+                else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
+                    try {
+                        evt.srcElement.releasePointerCapture(evt.pointerId);
+                    }
+                    catch (e) {
+                    }
+                    cacheSoloPointer = null;
+                    previousPinchDistance = 0;
+                    //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, 
+                    //but emptying completly pointers collection is required to fix a bug on iPhone : 
+                    //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers  
+                    //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
+                    pointA = pointB = undefined;
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                }
+                else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                    // One button down
+                    if (pointA && pointB === undefined) {
+                        if (_this.panningSensibility !== 0 &&
+                            ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
+                                (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
+                            _this.camera
+                                .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
+                            _this.camera
+                                .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
+                        }
+                        else {
+                            var offsetX = evt.clientX - cacheSoloPointer.x;
+                            var offsetY = evt.clientY - cacheSoloPointer.y;
+                            _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
+                            _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
+                        }
+                        cacheSoloPointer.x = evt.clientX;
+                        cacheSoloPointer.y = evt.clientY;
+                    }
+                    else if (pointA && pointB) {
+                        //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
+                        var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
+                        ed.x = evt.clientX;
+                        ed.y = evt.clientY;
+                        var direction = _this.pinchInwards ? 1 : -1;
+                        var distX = pointA.x - pointB.x;
+                        var distY = pointA.y - pointB.y;
+                        var pinchSquaredDistance = (distX * distX) + (distY * distY);
+                        if (previousPinchDistance === 0) {
+                            previousPinchDistance = pinchSquaredDistance;
+                            return;
+                        }
+                        if (pinchSquaredDistance !== previousPinchDistance) {
+                            _this.camera
+                                .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
+                                (_this.pinchPrecision *
+                                    ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
+                                    direction);
+                            previousPinchDistance = pinchSquaredDistance;
+                        }
+                    }
+                }
+            };
+            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
+            this._onContextMenu = function (evt) {
+                evt.preventDefault();
+            };
+            if (!this.camera._useCtrlForPanning) {
+                element.addEventListener("contextmenu", this._onContextMenu, false);
+            }
+            this._onLostFocus = function () {
+                //this._keys = [];
+                pointA = pointB = undefined;
+                previousPinchDistance = 0;
+                cacheSoloPointer = null;
+            };
+            this._onKeyDown = function (evt) {
+                _this._isCtrlPushed = evt.ctrlKey;
+            };
+            this._onKeyUp = function (evt) {
+                _this._isCtrlPushed = evt.ctrlKey;
+            };
+            this._onMouseMove = function (evt) {
+                if (!engine.isPointerLock) {
+                    return;
+                }
+                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
+                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
+                _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
+                _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
+                if (!noPreventDefault) {
+                    evt.preventDefault();
+                }
+            };
+            this._onGestureStart = function (e) {
+                if (window.MSGesture === undefined) {
+                    return;
+                }
+                if (!_this._MSGestureHandler) {
+                    _this._MSGestureHandler = new MSGesture();
+                    _this._MSGestureHandler.target = element;
+                }
+                _this._MSGestureHandler.addPointer(e.pointerId);
+            };
+            this._onGesture = function (e) {
+                _this.camera.radius *= e.scale;
+                if (e.preventDefault) {
+                    if (!noPreventDefault) {
+                        e.stopPropagation();
+                        e.preventDefault();
+                    }
+                }
+            };
+            element.addEventListener("mousemove", this._onMouseMove, false);
+            element.addEventListener("MSPointerDown", this._onGestureStart, false);
+            element.addEventListener("MSGestureChange", this._onGesture, false);
+            BABYLON.Tools.RegisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+        };
+        ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
+            if (element && this._observer) {
+                this.camera.getScene().onPointerObservable.remove(this._observer);
+                this._observer = null;
+                element.removeEventListener("contextmenu", this._onContextMenu);
+                element.removeEventListener("mousemove", this._onMouseMove);
+                element.removeEventListener("MSPointerDown", this._onGestureStart);
+                element.removeEventListener("MSGestureChange", this._onGesture);
+                this._isRightClick = false;
+                this._isCtrlPushed = false;
+                this.pinchInwards = true;
+                this._onKeyDown = null;
+                this._onKeyUp = null;
+                this._onMouseMove = null;
+                this._onGestureStart = null;
+                this._onGesture = null;
+                this._MSGestureHandler = null;
+                this._onLostFocus = null;
+                this._onContextMenu = null;
+            }
+            BABYLON.Tools.UnregisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+        };
+        ArcRotateCameraPointersInput.prototype.getTypeName = function () {
+            return "ArcRotateCameraPointersInput";
+        };
+        ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
+            return "pointers";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
+        return ArcRotateCameraPointersInput;
+    })();
+    BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
+    BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
+})(BABYLON || (BABYLON = {}));

+ 48 - 49
src/Cameras/Inputs/babylon.arcrotatecamera.input.vrdeviceorientation.js

@@ -1,49 +1,48 @@
-var BABYLON;
-(function (BABYLON) {
-    var ArcRotateCameraVRDeviceOrientationInput = (function () {
-        function ArcRotateCameraVRDeviceOrientationInput() {
-            this.alphaCorrection = 1;
-            this.betaCorrection = 1;
-            this.gammaCorrection = 1;
-            this._alpha = 0;
-            this._beta = 0;
-            this._gamma = 0;
-            this._dirty = false;
-            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
-        }
-        ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
-            this.camera.attachControl(element, noPreventDefault);
-            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
-            var camera = this.camera;
-            this._alpha = +evt.alpha | 0;
-            this._beta = +evt.beta | 0;
-            this._gamma = +evt.gamma | 0;
-            this._dirty = true;
-        };
-        ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
-            if (this._dirty) {
-                this._dirty = false;
-                if (this._gamma < 0) {
-                    this._gamma = 180 + this._gamma;
-                }
-                this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
-                this.camera.beta = (this._gamma / 180.0 * Math.PI);
-            }
-        };
-        ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
-            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
-            return "ArcRotateCameraVRDeviceOrientationInput";
-        };
-        ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
-            return "VRDeviceOrientation";
-        };
-        return ArcRotateCameraVRDeviceOrientationInput;
-    }());
-    BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
-    BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
+var BABYLON;
+(function (BABYLON) {
+    var ArcRotateCameraVRDeviceOrientationInput = (function () {
+        function ArcRotateCameraVRDeviceOrientationInput() {
+            this.alphaCorrection = 1;
+            this.betaCorrection = 1;
+            this.gammaCorrection = 1;
+            this._alpha = 0;
+            this._beta = 0;
+            this._gamma = 0;
+            this._dirty = false;
+            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
+        }
+        ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
+            this.camera.attachControl(element, noPreventDefault);
+            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
+            var camera = this.camera;
+            this._alpha = +evt.alpha | 0;
+            this._beta = +evt.beta | 0;
+            this._gamma = +evt.gamma | 0;
+            this._dirty = true;
+        };
+        ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
+            if (this._dirty) {
+                this._dirty = false;
+                if (this._gamma < 0) {
+                    this._gamma = 180 + this._gamma;
+                }
+                this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
+                this.camera.beta = (this._gamma / 180.0 * Math.PI);
+            }
+        };
+        ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
+            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
+            return "ArcRotateCameraVRDeviceOrientationInput";
+        };
+        ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
+            return "VRDeviceOrientation";
+        };
+        return ArcRotateCameraVRDeviceOrientationInput;
+    })();
+    BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
+    BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
+})(BABYLON || (BABYLON = {}));

+ 62 - 63
src/Cameras/Inputs/babylon.freecamera.input.deviceorientation.js

@@ -1,63 +1,62 @@
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraDeviceOrientationInput = (function () {
-        function FreeCameraDeviceOrientationInput() {
-            var _this = this;
-            this._screenOrientationAngle = 0;
-            this._screenQuaternion = new BABYLON.Quaternion();
-            this._alpha = 0;
-            this._beta = 0;
-            this._gamma = 0;
-            this._orientationChanged = function () {
-                _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
-                _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
-                _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
-            };
-            this._deviceOrientation = function (evt) {
-                _this._alpha = evt.alpha;
-                _this._beta = evt.beta;
-                _this._gamma = evt.gamma;
-            };
-            this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
-            this._orientationChanged();
-        }
-        Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
-            get: function () {
-                return this._camera;
-            },
-            set: function (camera) {
-                this._camera = camera;
-                if (!this._camera.rotationQuaternion)
-                    this._camera.rotationQuaternion = new BABYLON.Quaternion();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
-            window.addEventListener("orientationchange", this._orientationChanged);
-            window.addEventListener("deviceorientation", this._deviceOrientation);
-        };
-        FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
-            window.removeEventListener("orientationchange", this._orientationChanged);
-            window.removeEventListener("deviceorientation", this._deviceOrientation);
-        };
-        FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
-            BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
-            this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
-            this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
-            //Mirror on XY Plane
-            this._camera.rotationQuaternion.z *= -1;
-            this._camera.rotationQuaternion.w *= -1;
-        };
-        FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
-            return "FreeCameraDeviceOrientationInput";
-        };
-        FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
-            return "deviceOrientation";
-        };
-        return FreeCameraDeviceOrientationInput;
-    }());
-    BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
-    BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraDeviceOrientationInput = (function () {
+        function FreeCameraDeviceOrientationInput() {
+            var _this = this;
+            this._screenOrientationAngle = 0;
+            this._screenQuaternion = new BABYLON.Quaternion();
+            this._alpha = 0;
+            this._beta = 0;
+            this._gamma = 0;
+            this._orientationChanged = function () {
+                _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
+                _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
+                _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
+            };
+            this._deviceOrientation = function (evt) {
+                _this._alpha = evt.alpha;
+                _this._beta = evt.beta;
+                _this._gamma = evt.gamma;
+            };
+            this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
+            this._orientationChanged();
+        }
+        Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
+            get: function () {
+                return this._camera;
+            },
+            set: function (camera) {
+                this._camera = camera;
+                if (!this._camera.rotationQuaternion)
+                    this._camera.rotationQuaternion = new BABYLON.Quaternion();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
+            window.addEventListener("orientationchange", this._orientationChanged);
+            window.addEventListener("deviceorientation", this._deviceOrientation);
+        };
+        FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
+            window.removeEventListener("orientationchange", this._orientationChanged);
+            window.removeEventListener("deviceorientation", this._deviceOrientation);
+        };
+        FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
+            BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
+            this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
+            this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
+            //Mirror on XY Plane
+            this._camera.rotationQuaternion.z *= -1;
+            this._camera.rotationQuaternion.w *= -1;
+        };
+        FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
+            return "FreeCameraDeviceOrientationInput";
+        };
+        FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
+            return "deviceOrientation";
+        };
+        return FreeCameraDeviceOrientationInput;
+    })();
+    BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
+    BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
+})(BABYLON || (BABYLON = {}));

+ 66 - 67
src/Cameras/Inputs/babylon.freecamera.input.gamepad.js

@@ -1,67 +1,66 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraGamepadInput = (function () {
-        function FreeCameraGamepadInput() {
-            this.gamepadAngularSensibility = 200;
-            this.gamepadMoveSensibility = 40;
-        }
-        FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
-        };
-        FreeCameraGamepadInput.prototype.detachControl = function (element) {
-            if (this._gamepads) {
-                this._gamepads.dispose();
-            }
-            this.gamepad = null;
-        };
-        FreeCameraGamepadInput.prototype.checkInputs = function () {
-            if (this.gamepad) {
-                var camera = this.camera;
-                var LSValues = this.gamepad.leftStick;
-                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
-                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
-                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
-                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
-                var RSValues = this.gamepad.rightStick;
-                var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
-                var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
-                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
-                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
-                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
-                var speed = camera._computeLocalCameraSpeed() * 50.0;
-                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
-                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
-                camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
-            }
-        };
-        FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
-            // Only the first gamepad can control the camera
-            if (gamepad.index === 0) {
-                this.gamepad = gamepad;
-            }
-        };
-        FreeCameraGamepadInput.prototype.getTypeName = function () {
-            return "FreeCameraGamepadInput";
-        };
-        FreeCameraGamepadInput.prototype.getSimpleName = function () {
-            return "gamepad";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
-        return FreeCameraGamepadInput;
-    }());
-    BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
-    BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraGamepadInput = (function () {
+        function FreeCameraGamepadInput() {
+            this.gamepadAngularSensibility = 200;
+            this.gamepadMoveSensibility = 40;
+        }
+        FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
+        };
+        FreeCameraGamepadInput.prototype.detachControl = function (element) {
+            if (this._gamepads) {
+                this._gamepads.dispose();
+            }
+            this.gamepad = null;
+        };
+        FreeCameraGamepadInput.prototype.checkInputs = function () {
+            if (this.gamepad) {
+                var camera = this.camera;
+                var LSValues = this.gamepad.leftStick;
+                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
+                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
+                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
+                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
+                var RSValues = this.gamepad.rightStick;
+                var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
+                var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
+                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
+                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
+                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
+                var speed = camera._computeLocalCameraSpeed() * 50.0;
+                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
+                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
+                camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
+            }
+        };
+        FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
+            // Only the first gamepad can control the camera
+            if (gamepad.index === 0) {
+                this.gamepad = gamepad;
+            }
+        };
+        FreeCameraGamepadInput.prototype.getTypeName = function () {
+            return "FreeCameraGamepadInput";
+        };
+        FreeCameraGamepadInput.prototype.getSimpleName = function () {
+            return "gamepad";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
+        return FreeCameraGamepadInput;
+    })();
+    BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
+    BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
+})(BABYLON || (BABYLON = {}));

+ 117 - 118
src/Cameras/Inputs/babylon.freecamera.input.keyboard.js

@@ -1,118 +1,117 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraKeyboardMoveInput = (function () {
-        function FreeCameraKeyboardMoveInput() {
-            this._keys = [];
-            this.keysUp = [38];
-            this.keysDown = [40];
-            this.keysLeft = [37];
-            this.keysRight = [39];
-        }
-        FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            if (!this._onKeyDown) {
-                this._onKeyDown = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index === -1) {
-                            _this._keys.push(evt.keyCode);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                this._onKeyUp = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index >= 0) {
-                            _this._keys.splice(index, 1);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                BABYLON.Tools.RegisterTopRootEvents([
-                    { name: "keydown", handler: this._onKeyDown },
-                    { name: "keyup", handler: this._onKeyUp },
-                    { name: "blur", handler: this._onLostFocus }
-                ]);
-            }
-        };
-        FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
-            if (this._onKeyDown) {
-                BABYLON.Tools.UnregisterTopRootEvents([
-                    { name: "keydown", handler: this._onKeyDown },
-                    { name: "keyup", handler: this._onKeyUp },
-                    { name: "blur", handler: this._onLostFocus }
-                ]);
-                this._keys = [];
-                this._onKeyDown = null;
-                this._onKeyUp = null;
-            }
-        };
-        FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
-            if (this._onKeyDown) {
-                var camera = this.camera;
-                // Keyboard
-                for (var index = 0; index < this._keys.length; index++) {
-                    var keyCode = this._keys[index];
-                    var speed = camera._computeLocalCameraSpeed();
-                    if (this.keysLeft.indexOf(keyCode) !== -1) {
-                        camera._localDirection.copyFromFloats(-speed, 0, 0);
-                    }
-                    else if (this.keysUp.indexOf(keyCode) !== -1) {
-                        camera._localDirection.copyFromFloats(0, 0, speed);
-                    }
-                    else if (this.keysRight.indexOf(keyCode) !== -1) {
-                        camera._localDirection.copyFromFloats(speed, 0, 0);
-                    }
-                    else if (this.keysDown.indexOf(keyCode) !== -1) {
-                        camera._localDirection.copyFromFloats(0, 0, -speed);
-                    }
-                    camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
-                    BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
-                    camera.cameraDirection.addInPlace(camera._transformedDirection);
-                }
-            }
-        };
-        FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
-            return "FreeCameraKeyboardMoveInput";
-        };
-        FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
-            this._keys = [];
-        };
-        FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
-            return "keyboard";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
-        return FreeCameraKeyboardMoveInput;
-    }());
-    BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
-    BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraKeyboardMoveInput = (function () {
+        function FreeCameraKeyboardMoveInput() {
+            this._keys = [];
+            this.keysUp = [38];
+            this.keysDown = [40];
+            this.keysLeft = [37];
+            this.keysRight = [39];
+        }
+        FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            if (!this._onKeyDown) {
+                this._onKeyDown = function (evt) {
+                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                        var index = _this._keys.indexOf(evt.keyCode);
+                        if (index === -1) {
+                            _this._keys.push(evt.keyCode);
+                        }
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                };
+                this._onKeyUp = function (evt) {
+                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                        var index = _this._keys.indexOf(evt.keyCode);
+                        if (index >= 0) {
+                            _this._keys.splice(index, 1);
+                        }
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                };
+                BABYLON.Tools.RegisterTopRootEvents([
+                    { name: "keydown", handler: this._onKeyDown },
+                    { name: "keyup", handler: this._onKeyUp },
+                    { name: "blur", handler: this._onLostFocus }
+                ]);
+            }
+        };
+        FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
+            if (this._onKeyDown) {
+                BABYLON.Tools.UnregisterTopRootEvents([
+                    { name: "keydown", handler: this._onKeyDown },
+                    { name: "keyup", handler: this._onKeyUp },
+                    { name: "blur", handler: this._onLostFocus }
+                ]);
+                this._keys = [];
+                this._onKeyDown = null;
+                this._onKeyUp = null;
+            }
+        };
+        FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
+            if (this._onKeyDown) {
+                var camera = this.camera;
+                // Keyboard
+                for (var index = 0; index < this._keys.length; index++) {
+                    var keyCode = this._keys[index];
+                    var speed = camera._computeLocalCameraSpeed();
+                    if (this.keysLeft.indexOf(keyCode) !== -1) {
+                        camera._localDirection.copyFromFloats(-speed, 0, 0);
+                    }
+                    else if (this.keysUp.indexOf(keyCode) !== -1) {
+                        camera._localDirection.copyFromFloats(0, 0, speed);
+                    }
+                    else if (this.keysRight.indexOf(keyCode) !== -1) {
+                        camera._localDirection.copyFromFloats(speed, 0, 0);
+                    }
+                    else if (this.keysDown.indexOf(keyCode) !== -1) {
+                        camera._localDirection.copyFromFloats(0, 0, -speed);
+                    }
+                    camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
+                    BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
+                    camera.cameraDirection.addInPlace(camera._transformedDirection);
+                }
+            }
+        };
+        FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
+            return "FreeCameraKeyboardMoveInput";
+        };
+        FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
+            this._keys = [];
+        };
+        FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
+            return "keyboard";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
+        return FreeCameraKeyboardMoveInput;
+    })();
+    BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
+    BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
+})(BABYLON || (BABYLON = {}));

+ 98 - 99
src/Cameras/Inputs/babylon.freecamera.input.mouse.js

@@ -1,99 +1,98 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraMouseInput = (function () {
-        function FreeCameraMouseInput(touchEnabled) {
-            if (touchEnabled === void 0) { touchEnabled = true; }
-            this.touchEnabled = touchEnabled;
-            this.angularSensibility = 2000.0;
-        }
-        FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            if (!this._pointerInput) {
-                var camera = this.camera;
-                var engine = this.camera.getEngine();
-                this._pointerInput = function (p, s) {
-                    var evt = p.event;
-                    if (!_this.touchEnabled && evt.pointerType === "touch") {
-                        return;
-                    }
-                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
-                        try {
-                            evt.srcElement.setPointerCapture(evt.pointerId);
-                        }
-                        catch (e) {
-                        }
-                        _this.previousPosition = {
-                            x: evt.clientX,
-                            y: evt.clientY
-                        };
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
-                        try {
-                            evt.srcElement.releasePointerCapture(evt.pointerId);
-                        }
-                        catch (e) {
-                        }
-                        _this.previousPosition = null;
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
-                        if (!_this.previousPosition && !engine.isPointerLock) {
-                            return;
-                        }
-                        var offsetX;
-                        var offsetY;
-                        if (!engine.isPointerLock) {
-                            offsetX = evt.clientX - _this.previousPosition.x;
-                            offsetY = evt.clientY - _this.previousPosition.y;
-                        }
-                        else {
-                            offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
-                            offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
-                        }
-                        camera.cameraRotation.y += offsetX / _this.angularSensibility;
-                        camera.cameraRotation.x += offsetY / _this.angularSensibility;
-                        _this.previousPosition = {
-                            x: evt.clientX,
-                            y: evt.clientY
-                        };
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-            }
-            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
-        };
-        FreeCameraMouseInput.prototype.detachControl = function (element) {
-            if (this._observer && element) {
-                this.camera.getScene().onPointerObservable.remove(this._observer);
-                this._observer = null;
-                this.previousPosition = null;
-            }
-        };
-        FreeCameraMouseInput.prototype.getTypeName = function () {
-            return "FreeCameraMouseInput";
-        };
-        FreeCameraMouseInput.prototype.getSimpleName = function () {
-            return "mouse";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
-        return FreeCameraMouseInput;
-    }());
-    BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
-    BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.mouse.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraMouseInput = (function () {
+        function FreeCameraMouseInput(touchEnabled) {
+            if (touchEnabled === void 0) { touchEnabled = true; }
+            this.touchEnabled = touchEnabled;
+            this.angularSensibility = 2000.0;
+        }
+        FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            if (!this._pointerInput) {
+                var camera = this.camera;
+                var engine = this.camera.getEngine();
+                this._pointerInput = function (p, s) {
+                    var evt = p.event;
+                    if (!_this.touchEnabled && evt.pointerType === "touch") {
+                        return;
+                    }
+                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
+                        try {
+                            evt.srcElement.setPointerCapture(evt.pointerId);
+                        }
+                        catch (e) {
+                        }
+                        _this.previousPosition = {
+                            x: evt.clientX,
+                            y: evt.clientY
+                        };
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
+                        try {
+                            evt.srcElement.releasePointerCapture(evt.pointerId);
+                        }
+                        catch (e) {
+                        }
+                        _this.previousPosition = null;
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
+                        if (!_this.previousPosition && !engine.isPointerLock) {
+                            return;
+                        }
+                        var offsetX;
+                        var offsetY;
+                        if (!engine.isPointerLock) {
+                            offsetX = evt.clientX - _this.previousPosition.x;
+                            offsetY = evt.clientY - _this.previousPosition.y;
+                        }
+                        else {
+                            offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
+                            offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
+                        }
+                        camera.cameraRotation.y += offsetX / _this.angularSensibility;
+                        camera.cameraRotation.x += offsetY / _this.angularSensibility;
+                        _this.previousPosition = {
+                            x: evt.clientX,
+                            y: evt.clientY
+                        };
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                };
+            }
+            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
+        };
+        FreeCameraMouseInput.prototype.detachControl = function (element) {
+            if (this._observer && element) {
+                this.camera.getScene().onPointerObservable.remove(this._observer);
+                this._observer = null;
+                this.previousPosition = null;
+            }
+        };
+        FreeCameraMouseInput.prototype.getTypeName = function () {
+            return "FreeCameraMouseInput";
+        };
+        FreeCameraMouseInput.prototype.getSimpleName = function () {
+            return "mouse";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
+        return FreeCameraMouseInput;
+    })();
+    BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
+    BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
+})(BABYLON || (BABYLON = {}));

+ 122 - 123
src/Cameras/Inputs/babylon.freecamera.input.touch.js

@@ -1,123 +1,122 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraTouchInput = (function () {
-        function FreeCameraTouchInput() {
-            this._offsetX = null;
-            this._offsetY = null;
-            this._pointerCount = 0;
-            this._pointerPressed = [];
-            this.touchAngularSensibility = 200000.0;
-            this.touchMoveSensibility = 250.0;
-        }
-        FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            var previousPosition;
-            if (this._pointerInput === undefined) {
-                this._onLostFocus = function (evt) {
-                    _this._offsetX = null;
-                    _this._offsetY = null;
-                };
-                this._pointerInput = function (p, s) {
-                    var evt = p.event;
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                        _this._pointerPressed.push(evt.pointerId);
-                        if (_this._pointerPressed.length !== 1) {
-                            return;
-                        }
-                        previousPosition = {
-                            x: evt.clientX,
-                            y: evt.clientY
-                        };
-                    }
-                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                        var index = _this._pointerPressed.indexOf(evt.pointerId);
-                        if (index === -1) {
-                            return;
-                        }
-                        _this._pointerPressed.splice(index, 1);
-                        if (index != 0) {
-                            return;
-                        }
-                        previousPosition = null;
-                        _this._offsetX = null;
-                        _this._offsetY = null;
-                    }
-                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                        if (!previousPosition) {
-                            return;
-                        }
-                        var index = _this._pointerPressed.indexOf(evt.pointerId);
-                        if (index != 0) {
-                            return;
-                        }
-                        _this._offsetX = evt.clientX - previousPosition.x;
-                        _this._offsetY = -(evt.clientY - previousPosition.y);
-                    }
-                };
-            }
-            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
-            element.addEventListener("blur", this._onLostFocus);
-        };
-        FreeCameraTouchInput.prototype.detachControl = function (element) {
-            if (this._pointerInput && element) {
-                this.camera.getScene().onPointerObservable.remove(this._observer);
-                this._observer = null;
-                element.removeEventListener("blur", this._onLostFocus);
-                this._onLostFocus = null;
-                this._pointerPressed = [];
-                this._offsetX = null;
-                this._offsetY = null;
-                this._pointerCount = 0;
-            }
-        };
-        FreeCameraTouchInput.prototype.checkInputs = function () {
-            if (this._offsetX) {
-                var camera = this.camera;
-                camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
-                if (this._pointerPressed.length > 1) {
-                    camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
-                }
-                else {
-                    var speed = camera._computeLocalCameraSpeed();
-                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
-                    BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
-                    camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
-                }
-            }
-        };
-        FreeCameraTouchInput.prototype.getTypeName = function () {
-            return "FreeCameraTouchInput";
-        };
-        FreeCameraTouchInput.prototype.getSimpleName = function () {
-            return "touch";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
-        return FreeCameraTouchInput;
-    }());
-    BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
-    BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.touch.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraTouchInput = (function () {
+        function FreeCameraTouchInput() {
+            this._offsetX = null;
+            this._offsetY = null;
+            this._pointerCount = 0;
+            this._pointerPressed = [];
+            this.touchAngularSensibility = 200000.0;
+            this.touchMoveSensibility = 250.0;
+        }
+        FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            var previousPosition;
+            if (this._pointerInput === undefined) {
+                this._onLostFocus = function (evt) {
+                    _this._offsetX = null;
+                    _this._offsetY = null;
+                };
+                this._pointerInput = function (p, s) {
+                    var evt = p.event;
+                    if (evt.pointerType === "mouse") {
+                        return;
+                    }
+                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                        _this._pointerPressed.push(evt.pointerId);
+                        if (_this._pointerPressed.length !== 1) {
+                            return;
+                        }
+                        previousPosition = {
+                            x: evt.clientX,
+                            y: evt.clientY
+                        };
+                    }
+                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                        var index = _this._pointerPressed.indexOf(evt.pointerId);
+                        if (index === -1) {
+                            return;
+                        }
+                        _this._pointerPressed.splice(index, 1);
+                        if (index != 0) {
+                            return;
+                        }
+                        previousPosition = null;
+                        _this._offsetX = null;
+                        _this._offsetY = null;
+                    }
+                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                        if (!previousPosition) {
+                            return;
+                        }
+                        var index = _this._pointerPressed.indexOf(evt.pointerId);
+                        if (index != 0) {
+                            return;
+                        }
+                        _this._offsetX = evt.clientX - previousPosition.x;
+                        _this._offsetY = -(evt.clientY - previousPosition.y);
+                    }
+                };
+            }
+            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
+            element.addEventListener("blur", this._onLostFocus);
+        };
+        FreeCameraTouchInput.prototype.detachControl = function (element) {
+            if (this._pointerInput && element) {
+                this.camera.getScene().onPointerObservable.remove(this._observer);
+                this._observer = null;
+                element.removeEventListener("blur", this._onLostFocus);
+                this._onLostFocus = null;
+                this._pointerPressed = [];
+                this._offsetX = null;
+                this._offsetY = null;
+                this._pointerCount = 0;
+            }
+        };
+        FreeCameraTouchInput.prototype.checkInputs = function () {
+            if (this._offsetX) {
+                var camera = this.camera;
+                camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
+                if (this._pointerPressed.length > 1) {
+                    camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
+                }
+                else {
+                    var speed = camera._computeLocalCameraSpeed();
+                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
+                    BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
+                    camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
+                }
+            }
+        };
+        FreeCameraTouchInput.prototype.getTypeName = function () {
+            return "FreeCameraTouchInput";
+        };
+        FreeCameraTouchInput.prototype.getSimpleName = function () {
+            return "touch";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
+        return FreeCameraTouchInput;
+    })();
+    BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
+    BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
+})(BABYLON || (BABYLON = {}));

+ 54 - 55
src/Cameras/Inputs/babylon.freecamera.input.virtualjoystick.js

@@ -1,55 +1,54 @@
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraVirtualJoystickInput = (function () {
-        function FreeCameraVirtualJoystickInput() {
-        }
-        FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
-            return this._leftjoystick;
-        };
-        FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
-            return this._rightjoystick;
-        };
-        FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
-            if (this._leftjoystick) {
-                var camera = this.camera;
-                var speed = camera._computeLocalCameraSpeed() * 50;
-                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
-                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
-                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
-                camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
-                if (!this._leftjoystick.pressed) {
-                    this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
-                }
-                if (!this._rightjoystick.pressed) {
-                    this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
-                }
-            }
-        };
-        FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
-            this._leftjoystick = new BABYLON.VirtualJoystick(true);
-            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
-            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
-            this._leftjoystick.setJoystickSensibility(0.15);
-            this._rightjoystick = new BABYLON.VirtualJoystick(false);
-            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
-            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
-            this._rightjoystick.reverseUpDown = true;
-            this._rightjoystick.setJoystickSensibility(0.05);
-            this._rightjoystick.setJoystickColor("yellow");
-        };
-        FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
-            this._leftjoystick.releaseCanvas();
-            this._rightjoystick.releaseCanvas();
-        };
-        FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
-            return "FreeCameraVirtualJoystickInput";
-        };
-        FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
-            return "virtualJoystick";
-        };
-        return FreeCameraVirtualJoystickInput;
-    }());
-    BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
-    BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraVirtualJoystickInput = (function () {
+        function FreeCameraVirtualJoystickInput() {
+        }
+        FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
+            return this._leftjoystick;
+        };
+        FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
+            return this._rightjoystick;
+        };
+        FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
+            if (this._leftjoystick) {
+                var camera = this.camera;
+                var speed = camera._computeLocalCameraSpeed() * 50;
+                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
+                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
+                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
+                camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
+                if (!this._leftjoystick.pressed) {
+                    this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
+                }
+                if (!this._rightjoystick.pressed) {
+                    this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
+                }
+            }
+        };
+        FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
+            this._leftjoystick = new BABYLON.VirtualJoystick(true);
+            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
+            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
+            this._leftjoystick.setJoystickSensibility(0.15);
+            this._rightjoystick = new BABYLON.VirtualJoystick(false);
+            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
+            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
+            this._rightjoystick.reverseUpDown = true;
+            this._rightjoystick.setJoystickSensibility(0.05);
+            this._rightjoystick.setJoystickColor("yellow");
+        };
+        FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
+            this._leftjoystick.releaseCanvas();
+            this._rightjoystick.releaseCanvas();
+        };
+        FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
+            return "FreeCameraVirtualJoystickInput";
+        };
+        FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
+            return "virtualJoystick";
+        };
+        return FreeCameraVirtualJoystickInput;
+    })();
+    BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
+    BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
+})(BABYLON || (BABYLON = {}));

+ 53 - 54
src/Cameras/Inputs/babylon.freecamera.input.vrdeviceorientation.js

@@ -1,54 +1,53 @@
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraVRDeviceOrientationInput = (function () {
-        function FreeCameraVRDeviceOrientationInput() {
-            this.alphaCorrection = 1;
-            this.betaCorrection = 1;
-            this.gammaCorrection = 1;
-            this._alpha = 0;
-            this._beta = 0;
-            this._gamma = 0;
-            this._dirty = false;
-            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
-        }
-        FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
-            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
-            var camera = this.camera;
-            this._alpha = evt.alpha;
-            this._beta = evt.beta;
-            this._gamma = evt.gamma;
-            this._dirty = true;
-        };
-        FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
-            if (this._dirty) {
-                this._dirty = false;
-                var rotationX = this._gamma;
-                if (rotationX < 0) {
-                    rotationX = 90 + rotationX;
-                }
-                else {
-                    // Incline it in the correct angle.
-                    rotationX = 270 - rotationX;
-                }
-                this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
-                this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
-                this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
-            }
-        };
-        FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
-            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
-            return "FreeCameraVRDeviceOrientationInput";
-        };
-        FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
-            return "VRDeviceOrientation";
-        };
-        return FreeCameraVRDeviceOrientationInput;
-    }());
-    BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
-    BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freecamera.input.vrdeviceorientation.js.map
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraVRDeviceOrientationInput = (function () {
+        function FreeCameraVRDeviceOrientationInput() {
+            this.alphaCorrection = 1;
+            this.betaCorrection = 1;
+            this.gammaCorrection = 1;
+            this._alpha = 0;
+            this._beta = 0;
+            this._gamma = 0;
+            this._dirty = false;
+            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
+        }
+        FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
+            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
+            var camera = this.camera;
+            this._alpha = evt.alpha;
+            this._beta = evt.beta;
+            this._gamma = evt.gamma;
+            this._dirty = true;
+        };
+        FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
+            if (this._dirty) {
+                this._dirty = false;
+                var rotationX = this._gamma;
+                if (rotationX < 0) {
+                    rotationX = 90 + rotationX;
+                }
+                else {
+                    // Incline it in the correct angle.
+                    rotationX = 270 - rotationX;
+                }
+                this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
+                this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
+                this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
+            }
+        };
+        FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
+            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
+            return "FreeCameraVRDeviceOrientationInput";
+        };
+        FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
+            return "VRDeviceOrientation";
+        };
+        return FreeCameraVRDeviceOrientationInput;
+    })();
+    BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
+    BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
+})(BABYLON || (BABYLON = {}));

+ 72 - 73
src/Cameras/VR/babylon.vrCameraMetrics.js

@@ -1,73 +1,72 @@
-var BABYLON;
-(function (BABYLON) {
-    var VRCameraMetrics = (function () {
-        function VRCameraMetrics() {
-            this.compensateDistortion = true;
-        }
-        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
-            get: function () {
-                return this.hResolution / (2 * this.vResolution);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
-            get: function () {
-                return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
-            get: function () {
-                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
-                var h = (4 * meters) / this.hScreenSize;
-                return BABYLON.Matrix.Translation(h, 0, 0);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
-            get: function () {
-                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
-                var h = (4 * meters) / this.hScreenSize;
-                return BABYLON.Matrix.Translation(-h, 0, 0);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
-            get: function () {
-                return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
-            get: function () {
-                return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        VRCameraMetrics.GetDefault = function () {
-            var result = new VRCameraMetrics();
-            result.hResolution = 1280;
-            result.vResolution = 800;
-            result.hScreenSize = 0.149759993;
-            result.vScreenSize = 0.0935999975;
-            result.vScreenCenter = 0.0467999987,
-                result.eyeToScreenDistance = 0.0410000011;
-            result.lensSeparationDistance = 0.0635000020;
-            result.interpupillaryDistance = 0.0640000030;
-            result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
-            result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
-            result.postProcessScaleFactor = 1.714605507808412;
-            result.lensCenterOffset = 0.151976421;
-            return result;
-        };
-        return VRCameraMetrics;
-    }());
-    BABYLON.VRCameraMetrics = VRCameraMetrics;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.vrCameraMetrics.js.map
+var BABYLON;
+(function (BABYLON) {
+    var VRCameraMetrics = (function () {
+        function VRCameraMetrics() {
+            this.compensateDistortion = true;
+        }
+        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
+            get: function () {
+                return this.hResolution / (2 * this.vResolution);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
+            get: function () {
+                return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
+            get: function () {
+                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
+                var h = (4 * meters) / this.hScreenSize;
+                return BABYLON.Matrix.Translation(h, 0, 0);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
+            get: function () {
+                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
+                var h = (4 * meters) / this.hScreenSize;
+                return BABYLON.Matrix.Translation(-h, 0, 0);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
+            get: function () {
+                return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
+            get: function () {
+                return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        VRCameraMetrics.GetDefault = function () {
+            var result = new VRCameraMetrics();
+            result.hResolution = 1280;
+            result.vResolution = 800;
+            result.hScreenSize = 0.149759993;
+            result.vScreenSize = 0.0935999975;
+            result.vScreenCenter = 0.0467999987,
+                result.eyeToScreenDistance = 0.0410000011;
+            result.lensSeparationDistance = 0.0635000020;
+            result.interpupillaryDistance = 0.0640000030;
+            result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
+            result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
+            result.postProcessScaleFactor = 1.714605507808412;
+            result.lensCenterOffset = 0.151976421;
+            return result;
+        };
+        return VRCameraMetrics;
+    })();
+    BABYLON.VRCameraMetrics = VRCameraMetrics;
+})(BABYLON || (BABYLON = {}));

+ 41 - 42
src/Cameras/VR/babylon.vrDeviceOrientationCamera.js

@@ -1,42 +1,41 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var VRDeviceOrientationFreeCamera = (function (_super) {
-        __extends(VRDeviceOrientationFreeCamera, _super);
-        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this.rotationQuaternion = new BABYLON.Quaternion();
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this.inputs.addDeviceOrientation();
-        }
-        VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
-            return "VRDeviceOrientationFreeCamera";
-        };
-        return VRDeviceOrientationFreeCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
-    var VRDeviceOrientationArcRotateCamera = (function (_super) {
-        __extends(VRDeviceOrientationArcRotateCamera, _super);
-        function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, alpha, beta, radius, target, scene);
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this.inputs.addVRDeviceOrientation();
-        }
-        VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
-            return "VRDeviceOrientationArcRotateCamera";
-        };
-        return VRDeviceOrientationArcRotateCamera;
-    }(BABYLON.ArcRotateCamera));
-    BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var VRDeviceOrientationFreeCamera = (function (_super) {
+        __extends(VRDeviceOrientationFreeCamera, _super);
+        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this.rotationQuaternion = new BABYLON.Quaternion();
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this.inputs.addDeviceOrientation();
+        }
+        VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
+            return "VRDeviceOrientationFreeCamera";
+        };
+        return VRDeviceOrientationFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
+    var VRDeviceOrientationArcRotateCamera = (function (_super) {
+        __extends(VRDeviceOrientationArcRotateCamera, _super);
+        function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, alpha, beta, radius, target, scene);
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this.inputs.addVRDeviceOrientation();
+        }
+        VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
+            return "VRDeviceOrientationArcRotateCamera";
+        };
+        return VRDeviceOrientationArcRotateCamera;
+    })(BABYLON.ArcRotateCamera);
+    BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
+})(BABYLON || (BABYLON = {}));

+ 80 - 81
src/Cameras/VR/babylon.webVRCamera.js

@@ -1,81 +1,80 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var WebVRFreeCamera = (function (_super) {
-        __extends(WebVRFreeCamera, _super);
-        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this._hmdDevice = null;
-            this._sensorDevice = null;
-            this._cacheState = null;
-            this._vrEnabled = false;
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this._getWebVRDevices = this._getWebVRDevices.bind(this);
-            this.rotationQuaternion = new BABYLON.Quaternion();
-        }
-        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
-            var size = devices.length;
-            var i = 0;
-            // Reset devices.
-            this._sensorDevice = null;
-            this._hmdDevice = null;
-            // Search for a HmdDevice.
-            while (i < size && this._hmdDevice === null) {
-                if (devices[i] instanceof HMDVRDevice) {
-                    this._hmdDevice = devices[i];
-                }
-                i++;
-            }
-            i = 0;
-            while (i < size && this._sensorDevice === null) {
-                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
-                    this._sensorDevice = devices[i];
-                }
-                i++;
-            }
-            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
-        };
-        WebVRFreeCamera.prototype._checkInputs = function () {
-            if (this._vrEnabled) {
-                this._cacheState = this._sensorDevice.getState();
-                this.rotationQuaternion.copyFrom(this._cacheState.orientation);
-                //Flip in XY plane
-                this.rotationQuaternion.z *= -1;
-                this.rotationQuaternion.w *= -1;
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
-            if (navigator.getVRDevices) {
-                navigator.getVRDevices().then(this._getWebVRDevices);
-            }
-            else if (navigator.mozGetVRDevices) {
-                navigator.mozGetVRDevices(this._getWebVRDevices);
-            }
-        };
-        WebVRFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            this._vrEnabled = false;
-        };
-        WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
-            if (!this._hmdDevice)
-                return;
-            this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
-        };
-        WebVRFreeCamera.prototype.getTypeName = function () {
-            return "WebVRFreeCamera";
-        };
-        return WebVRFreeCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.webVRCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var WebVRFreeCamera = (function (_super) {
+        __extends(WebVRFreeCamera, _super);
+        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this._hmdDevice = null;
+            this._sensorDevice = null;
+            this._cacheState = null;
+            this._vrEnabled = false;
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this._getWebVRDevices = this._getWebVRDevices.bind(this);
+            this.rotationQuaternion = new BABYLON.Quaternion();
+        }
+        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
+            var size = devices.length;
+            var i = 0;
+            // Reset devices.
+            this._sensorDevice = null;
+            this._hmdDevice = null;
+            // Search for a HmdDevice.
+            while (i < size && this._hmdDevice === null) {
+                if (devices[i] instanceof HMDVRDevice) {
+                    this._hmdDevice = devices[i];
+                }
+                i++;
+            }
+            i = 0;
+            while (i < size && this._sensorDevice === null) {
+                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
+                    this._sensorDevice = devices[i];
+                }
+                i++;
+            }
+            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
+        };
+        WebVRFreeCamera.prototype._checkInputs = function () {
+            if (this._vrEnabled) {
+                this._cacheState = this._sensorDevice.getState();
+                this.rotationQuaternion.copyFrom(this._cacheState.orientation);
+                //Flip in XY plane
+                this.rotationQuaternion.z *= -1;
+                this.rotationQuaternion.w *= -1;
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
+            if (navigator.getVRDevices) {
+                navigator.getVRDevices().then(this._getWebVRDevices);
+            }
+            else if (navigator.mozGetVRDevices) {
+                navigator.mozGetVRDevices(this._getWebVRDevices);
+            }
+        };
+        WebVRFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            this._vrEnabled = false;
+        };
+        WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
+            if (!this._hmdDevice)
+                return;
+            this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
+        };
+        WebVRFreeCamera.prototype.getTypeName = function () {
+            return "WebVRFreeCamera";
+        };
+        return WebVRFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 546 - 547
src/Cameras/babylon.arcRotateCamera.js


+ 36 - 37
src/Cameras/babylon.arcRotateCameraInputsManager.js

@@ -1,37 +1,36 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var ArcRotateCameraInputsManager = (function (_super) {
-        __extends(ArcRotateCameraInputsManager, _super);
-        function ArcRotateCameraInputsManager(camera) {
-            _super.call(this, camera);
-        }
-        ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
-            this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
-            return this;
-        };
-        ArcRotateCameraInputsManager.prototype.addPointers = function () {
-            this.add(new BABYLON.ArcRotateCameraPointersInput());
-            return this;
-        };
-        ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
-            this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
-            return this;
-        };
-        ArcRotateCameraInputsManager.prototype.addGamepad = function () {
-            this.add(new BABYLON.ArcRotateCameraGamepadInput());
-            return this;
-        };
-        ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
-            this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
-            return this;
-        };
-        return ArcRotateCameraInputsManager;
-    }(BABYLON.CameraInputsManager));
-    BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var ArcRotateCameraInputsManager = (function (_super) {
+        __extends(ArcRotateCameraInputsManager, _super);
+        function ArcRotateCameraInputsManager(camera) {
+            _super.call(this, camera);
+        }
+        ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
+            this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
+            return this;
+        };
+        ArcRotateCameraInputsManager.prototype.addPointers = function () {
+            this.add(new BABYLON.ArcRotateCameraPointersInput());
+            return this;
+        };
+        ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
+            this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
+            return this;
+        };
+        ArcRotateCameraInputsManager.prototype.addGamepad = function () {
+            this.add(new BABYLON.ArcRotateCameraGamepadInput());
+            return this;
+        };
+        ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
+            this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
+            return this;
+        };
+        return ArcRotateCameraInputsManager;
+    })(BABYLON.CameraInputsManager);
+    BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 620 - 621
src/Cameras/babylon.camera.js


+ 133 - 134
src/Cameras/babylon.cameraInputsManager.js

@@ -1,134 +1,133 @@
-var BABYLON;
-(function (BABYLON) {
-    BABYLON.CameraInputTypes = {};
-    var CameraInputsManager = (function () {
-        function CameraInputsManager(camera) {
-            this.attached = {};
-            this.camera = camera;
-            this.checkInputs = function () { };
-        }
-        CameraInputsManager.prototype.add = function (input) {
-            var type = input.getSimpleName();
-            if (this.attached[type]) {
-                BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
-                return;
-            }
-            this.attached[type] = input;
-            input.camera = this.camera;
-            //for checkInputs, we are dynamically creating a function
-            //the goal is to avoid the performance penalty of looping for inputs in the render loop
-            if (input.checkInputs) {
-                this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
-            }
-            if (this.attachedElement) {
-                input.attachControl(this.attachedElement);
-            }
-        };
-        CameraInputsManager.prototype.remove = function (inputToRemove) {
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                if (input === inputToRemove) {
-                    input.detachControl(this.attachedElement);
-                    delete this.attached[cam];
-                    this.rebuildInputCheck();
-                }
-            }
-        };
-        CameraInputsManager.prototype.removeByType = function (inputType) {
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                if (input.getTypeName() === inputType) {
-                    input.detachControl(this.attachedElement);
-                    delete this.attached[cam];
-                    this.rebuildInputCheck();
-                }
-            }
-        };
-        CameraInputsManager.prototype._addCheckInputs = function (fn) {
-            var current = this.checkInputs;
-            return function () {
-                current();
-                fn();
-            };
-        };
-        CameraInputsManager.prototype.attachInput = function (input) {
-            input.attachControl(this.attachedElement, this.noPreventDefault);
-        };
-        CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
-            if (this.attachedElement) {
-                return;
-            }
-            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
-            this.attachedElement = element;
-            this.noPreventDefault = noPreventDefault;
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                this.attached[cam].attachControl(element, noPreventDefault);
-            }
-        };
-        CameraInputsManager.prototype.detachElement = function (element) {
-            if (this.attachedElement !== element) {
-                return;
-            }
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                this.attached[cam].detachControl(element);
-            }
-            this.attachedElement = null;
-        };
-        CameraInputsManager.prototype.rebuildInputCheck = function () {
-            this.checkInputs = function () { };
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                if (input.checkInputs) {
-                    this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
-                }
-            }
-        };
-        CameraInputsManager.prototype.clear = function () {
-            if (this.attachedElement) {
-                this.detachElement(this.attachedElement);
-            }
-            this.attached = {};
-            this.attachedElement = null;
-            this.checkInputs = function () { };
-        };
-        CameraInputsManager.prototype.serialize = function (serializedCamera) {
-            var inputs = {};
-            for (var cam in this.attached) {
-                var input = this.attached[cam];
-                var res = BABYLON.SerializationHelper.Serialize(input);
-                inputs[input.getTypeName()] = res;
-            }
-            serializedCamera.inputsmgr = inputs;
-        };
-        CameraInputsManager.prototype.parse = function (parsedCamera) {
-            var parsedInputs = parsedCamera.inputsmgr;
-            if (parsedInputs) {
-                this.clear();
-                for (var n in parsedInputs) {
-                    var construct = BABYLON.CameraInputTypes[n];
-                    if (construct) {
-                        var parsedinput = parsedInputs[n];
-                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
-                        this.add(input);
-                    }
-                }
-            }
-            else {
-                //2016-03-08 this part is for managing backward compatibility
-                for (var n in this.attached) {
-                    var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
-                    if (construct) {
-                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
-                        this.remove(this.attached[n]);
-                        this.add(input);
-                    }
-                }
-            }
-        };
-        return CameraInputsManager;
-    }());
-    BABYLON.CameraInputsManager = CameraInputsManager;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.cameraInputsManager.js.map
+var BABYLON;
+(function (BABYLON) {
+    BABYLON.CameraInputTypes = {};
+    var CameraInputsManager = (function () {
+        function CameraInputsManager(camera) {
+            this.attached = {};
+            this.camera = camera;
+            this.checkInputs = function () { };
+        }
+        CameraInputsManager.prototype.add = function (input) {
+            var type = input.getSimpleName();
+            if (this.attached[type]) {
+                BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
+                return;
+            }
+            this.attached[type] = input;
+            input.camera = this.camera;
+            //for checkInputs, we are dynamically creating a function
+            //the goal is to avoid the performance penalty of looping for inputs in the render loop
+            if (input.checkInputs) {
+                this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
+            }
+            if (this.attachedElement) {
+                input.attachControl(this.attachedElement);
+            }
+        };
+        CameraInputsManager.prototype.remove = function (inputToRemove) {
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                if (input === inputToRemove) {
+                    input.detachControl(this.attachedElement);
+                    delete this.attached[cam];
+                    this.rebuildInputCheck();
+                }
+            }
+        };
+        CameraInputsManager.prototype.removeByType = function (inputType) {
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                if (input.getTypeName() === inputType) {
+                    input.detachControl(this.attachedElement);
+                    delete this.attached[cam];
+                    this.rebuildInputCheck();
+                }
+            }
+        };
+        CameraInputsManager.prototype._addCheckInputs = function (fn) {
+            var current = this.checkInputs;
+            return function () {
+                current();
+                fn();
+            };
+        };
+        CameraInputsManager.prototype.attachInput = function (input) {
+            input.attachControl(this.attachedElement, this.noPreventDefault);
+        };
+        CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
+            if (this.attachedElement) {
+                return;
+            }
+            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
+            this.attachedElement = element;
+            this.noPreventDefault = noPreventDefault;
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                this.attached[cam].attachControl(element, noPreventDefault);
+            }
+        };
+        CameraInputsManager.prototype.detachElement = function (element) {
+            if (this.attachedElement !== element) {
+                return;
+            }
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                this.attached[cam].detachControl(element);
+            }
+            this.attachedElement = null;
+        };
+        CameraInputsManager.prototype.rebuildInputCheck = function () {
+            this.checkInputs = function () { };
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                if (input.checkInputs) {
+                    this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
+                }
+            }
+        };
+        CameraInputsManager.prototype.clear = function () {
+            if (this.attachedElement) {
+                this.detachElement(this.attachedElement);
+            }
+            this.attached = {};
+            this.attachedElement = null;
+            this.checkInputs = function () { };
+        };
+        CameraInputsManager.prototype.serialize = function (serializedCamera) {
+            var inputs = {};
+            for (var cam in this.attached) {
+                var input = this.attached[cam];
+                var res = BABYLON.SerializationHelper.Serialize(input);
+                inputs[input.getTypeName()] = res;
+            }
+            serializedCamera.inputsmgr = inputs;
+        };
+        CameraInputsManager.prototype.parse = function (parsedCamera) {
+            var parsedInputs = parsedCamera.inputsmgr;
+            if (parsedInputs) {
+                this.clear();
+                for (var n in parsedInputs) {
+                    var construct = BABYLON.CameraInputTypes[n];
+                    if (construct) {
+                        var parsedinput = parsedInputs[n];
+                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
+                        this.add(input);
+                    }
+                }
+            }
+            else {
+                //2016-03-08 this part is for managing backward compatibility
+                for (var n in this.attached) {
+                    var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
+                    if (construct) {
+                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
+                        this.remove(this.attached[n]);
+                        this.add(input);
+                    }
+                }
+            }
+        };
+        return CameraInputsManager;
+    })();
+    BABYLON.CameraInputsManager = CameraInputsManager;
+})(BABYLON || (BABYLON = {}));

+ 41 - 42
src/Cameras/babylon.deviceOrientationCamera.js

@@ -1,42 +1,41 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var DeviceOrientationCamera = (function (_super) {
-        __extends(DeviceOrientationCamera, _super);
-        //-- end properties for backward compatibility for inputs
-        function DeviceOrientationCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.inputs.addDeviceOrientation();
-        }
-        Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
-            //-- Begin properties for backward compatibility for inputs
-            get: function () {
-                return 0;
-            },
-            set: function (value) {
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
-            get: function () {
-                return 0;
-            },
-            set: function (value) {
-            },
-            enumerable: true,
-            configurable: true
-        });
-        DeviceOrientationCamera.prototype.getTypeName = function () {
-            return "DeviceOrientationCamera";
-        };
-        return DeviceOrientationCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.deviceOrientationCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var DeviceOrientationCamera = (function (_super) {
+        __extends(DeviceOrientationCamera, _super);
+        //-- end properties for backward compatibility for inputs
+        function DeviceOrientationCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addDeviceOrientation();
+        }
+        Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
+            //-- Begin properties for backward compatibility for inputs
+            get: function () {
+                return 0;
+            },
+            set: function (value) {
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
+            get: function () {
+                return 0;
+            },
+            set: function (value) {
+            },
+            enumerable: true,
+            configurable: true
+        });
+        DeviceOrientationCamera.prototype.getTypeName = function () {
+            return "DeviceOrientationCamera";
+        };
+        return DeviceOrientationCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
+})(BABYLON || (BABYLON = {}));

+ 117 - 118
src/Cameras/babylon.followCamera.js

@@ -1,118 +1,117 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FollowCamera = (function (_super) {
-        __extends(FollowCamera, _super);
-        function FollowCamera(name, position, scene, target) {
-            _super.call(this, name, position, scene);
-            this.radius = 12;
-            this.rotationOffset = 0;
-            this.heightOffset = 4;
-            this.cameraAcceleration = 0.05;
-            this.maxCameraSpeed = 20;
-            this.target = target;
-        }
-        FollowCamera.prototype.getRadians = function (degrees) {
-            return degrees * Math.PI / 180;
-        };
-        FollowCamera.prototype.follow = function (cameraTarget) {
-            if (!cameraTarget)
-                return;
-            var yRotation;
-            if (cameraTarget.rotationQuaternion) {
-                var rotMatrix = new BABYLON.Matrix();
-                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
-                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
-            }
-            else {
-                yRotation = cameraTarget.rotation.y;
-            }
-            var radians = this.getRadians(this.rotationOffset) + yRotation;
-            var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
-            var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
-            var dx = targetX - this.position.x;
-            var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
-            var dz = (targetZ) - this.position.z;
-            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
-            var vy = dy * this.cameraAcceleration;
-            var vz = dz * this.cameraAcceleration * 2;
-            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
-                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
-                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
-                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
-            this.setTarget(cameraTarget.position);
-        };
-        FollowCamera.prototype._checkInputs = function () {
-            _super.prototype._checkInputs.call(this);
-            this.follow(this.target);
-        };
-        FollowCamera.prototype.getTypeName = function () {
-            return "FollowCamera";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], FollowCamera.prototype, "radius", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FollowCamera.prototype, "rotationOffset", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FollowCamera.prototype, "heightOffset", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FollowCamera.prototype, "cameraAcceleration", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FollowCamera.prototype, "maxCameraSpeed", void 0);
-        __decorate([
-            BABYLON.serializeAsMeshReference("lockedTargetId")
-        ], FollowCamera.prototype, "target", void 0);
-        return FollowCamera;
-    }(BABYLON.TargetCamera));
-    BABYLON.FollowCamera = FollowCamera;
-    var ArcFollowCamera = (function (_super) {
-        __extends(ArcFollowCamera, _super);
-        function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
-            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
-            this.alpha = alpha;
-            this.beta = beta;
-            this.radius = radius;
-            this.target = target;
-            this._cartesianCoordinates = BABYLON.Vector3.Zero();
-            this.follow();
-        }
-        ArcFollowCamera.prototype.follow = function () {
-            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
-            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
-            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
-            this.position = this.target.position.add(this._cartesianCoordinates);
-            this.setTarget(this.target.position);
-        };
-        ArcFollowCamera.prototype._checkInputs = function () {
-            _super.prototype._checkInputs.call(this);
-            this.follow();
-        };
-        ArcFollowCamera.prototype.getTypeName = function () {
-            return "ArcFollowCamera";
-        };
-        return ArcFollowCamera;
-    }(BABYLON.TargetCamera));
-    BABYLON.ArcFollowCamera = ArcFollowCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.followCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FollowCamera = (function (_super) {
+        __extends(FollowCamera, _super);
+        function FollowCamera(name, position, scene, target) {
+            _super.call(this, name, position, scene);
+            this.radius = 12;
+            this.rotationOffset = 0;
+            this.heightOffset = 4;
+            this.cameraAcceleration = 0.05;
+            this.maxCameraSpeed = 20;
+            this.target = target;
+        }
+        FollowCamera.prototype.getRadians = function (degrees) {
+            return degrees * Math.PI / 180;
+        };
+        FollowCamera.prototype.follow = function (cameraTarget) {
+            if (!cameraTarget)
+                return;
+            var yRotation;
+            if (cameraTarget.rotationQuaternion) {
+                var rotMatrix = new BABYLON.Matrix();
+                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
+                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
+            }
+            else {
+                yRotation = cameraTarget.rotation.y;
+            }
+            var radians = this.getRadians(this.rotationOffset) + yRotation;
+            var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
+            var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
+            var dx = targetX - this.position.x;
+            var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
+            var dz = (targetZ) - this.position.z;
+            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
+            var vy = dy * this.cameraAcceleration;
+            var vz = dz * this.cameraAcceleration * 2;
+            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
+                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
+                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
+                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
+            this.setTarget(cameraTarget.position);
+        };
+        FollowCamera.prototype._checkInputs = function () {
+            _super.prototype._checkInputs.call(this);
+            this.follow(this.target);
+        };
+        FollowCamera.prototype.getTypeName = function () {
+            return "FollowCamera";
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], FollowCamera.prototype, "radius", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FollowCamera.prototype, "rotationOffset", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FollowCamera.prototype, "heightOffset", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FollowCamera.prototype, "cameraAcceleration", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FollowCamera.prototype, "maxCameraSpeed", void 0);
+        __decorate([
+            BABYLON.serializeAsMeshReference("lockedTargetId")
+        ], FollowCamera.prototype, "target", void 0);
+        return FollowCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.FollowCamera = FollowCamera;
+    var ArcFollowCamera = (function (_super) {
+        __extends(ArcFollowCamera, _super);
+        function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
+            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
+            this.alpha = alpha;
+            this.beta = beta;
+            this.radius = radius;
+            this.target = target;
+            this._cartesianCoordinates = BABYLON.Vector3.Zero();
+            this.follow();
+        }
+        ArcFollowCamera.prototype.follow = function () {
+            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
+            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
+            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
+            this.position = this.target.position.add(this._cartesianCoordinates);
+            this.setTarget(this.target.position);
+        };
+        ArcFollowCamera.prototype._checkInputs = function () {
+            _super.prototype._checkInputs.call(this);
+            this.follow();
+        };
+        ArcFollowCamera.prototype.getTypeName = function () {
+            return "ArcFollowCamera";
+        };
+        return ArcFollowCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.ArcFollowCamera = ArcFollowCamera;
+})(BABYLON || (BABYLON = {}));

+ 185 - 186
src/Cameras/babylon.freeCamera.js

@@ -1,186 +1,185 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCamera = (function (_super) {
-        __extends(FreeCamera, _super);
-        function FreeCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
-            this.checkCollisions = false;
-            this.applyGravity = false;
-            this._collider = new BABYLON.Collider();
-            this._needMoveForGravity = false;
-            this._oldPosition = BABYLON.Vector3.Zero();
-            this._diffPosition = BABYLON.Vector3.Zero();
-            this._newPosition = BABYLON.Vector3.Zero();
-            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
-                if (collidedMesh === void 0) { collidedMesh = null; }
-                //TODO move this to the collision coordinator!
-                if (_this.getScene().workerCollisions)
-                    newPosition.multiplyInPlace(_this._collider.radius);
-                var updatePosition = function (newPos) {
-                    _this._newPosition.copyFrom(newPos);
-                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
-                    var oldPosition = _this.position.clone();
-                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
-                        _this.position.addInPlace(_this._diffPosition);
-                        if (_this.onCollide && collidedMesh) {
-                            _this.onCollide(collidedMesh);
-                        }
-                    }
-                };
-                updatePosition(newPosition);
-            };
-            this.inputs = new BABYLON.FreeCameraInputsManager(this);
-            this.inputs.addKeyboard().addMouse();
-        }
-        Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
-            //-- begin properties for backward compatibility for inputs
-            get: function () {
-                var mouse = this.inputs.attached["mouse"];
-                if (mouse)
-                    return mouse.angularSensibility;
-            },
-            set: function (value) {
-                var mouse = this.inputs.attached["mouse"];
-                if (mouse)
-                    mouse.angularSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FreeCamera.prototype, "keysUp", {
-            get: function () {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    return keyboard.keysUp;
-            },
-            set: function (value) {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    keyboard.keysUp = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FreeCamera.prototype, "keysDown", {
-            get: function () {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    return keyboard.keysDown;
-            },
-            set: function (value) {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    keyboard.keysDown = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FreeCamera.prototype, "keysLeft", {
-            get: function () {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    return keyboard.keysLeft;
-            },
-            set: function (value) {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    keyboard.keysLeft = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FreeCamera.prototype, "keysRight", {
-            get: function () {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    return keyboard.keysRight;
-            },
-            set: function (value) {
-                var keyboard = this.inputs.attached["keyboard"];
-                if (keyboard)
-                    keyboard.keysRight = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Controls
-        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            this.inputs.attachElement(element, noPreventDefault);
-        };
-        FreeCamera.prototype.detachControl = function (element) {
-            this.inputs.detachElement(element);
-            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
-            this.cameraRotation = new BABYLON.Vector2(0, 0);
-        };
-        FreeCamera.prototype._collideWithWorld = function (velocity) {
-            var globalPosition;
-            if (this.parent) {
-                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
-            }
-            else {
-                globalPosition = this.position;
-            }
-            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
-            this._collider.radius = this.ellipsoid;
-            //no need for clone, as long as gravity is not on.
-            var actualVelocity = velocity;
-            //add gravity to the velocity to prevent the dual-collision checking
-            if (this.applyGravity) {
-                //this prevents mending with cameraDirection, a global variable of the free camera class.
-                actualVelocity = velocity.add(this.getScene().gravity);
-            }
-            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
-        };
-        FreeCamera.prototype._checkInputs = function () {
-            if (!this._localDirection) {
-                this._localDirection = BABYLON.Vector3.Zero();
-                this._transformedDirection = BABYLON.Vector3.Zero();
-            }
-            this.inputs.checkInputs();
-            _super.prototype._checkInputs.call(this);
-        };
-        FreeCamera.prototype._decideIfNeedsToMove = function () {
-            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        };
-        FreeCamera.prototype._updatePosition = function () {
-            if (this.checkCollisions && this.getScene().collisionsEnabled) {
-                this._collideWithWorld(this.cameraDirection);
-            }
-            else {
-                this.position.addInPlace(this.cameraDirection);
-            }
-        };
-        FreeCamera.prototype.dispose = function () {
-            this.inputs.clear();
-            _super.prototype.dispose.call(this);
-        };
-        FreeCamera.prototype.getTypeName = function () {
-            return "FreeCamera";
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], FreeCamera.prototype, "ellipsoid", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "checkCollisions", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "applyGravity", void 0);
-        return FreeCamera;
-    }(BABYLON.TargetCamera));
-    BABYLON.FreeCamera = FreeCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freeCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCamera = (function (_super) {
+        __extends(FreeCamera, _super);
+        function FreeCamera(name, position, scene) {
+            var _this = this;
+            _super.call(this, name, position, scene);
+            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
+            this.checkCollisions = false;
+            this.applyGravity = false;
+            this._collider = new BABYLON.Collider();
+            this._needMoveForGravity = false;
+            this._oldPosition = BABYLON.Vector3.Zero();
+            this._diffPosition = BABYLON.Vector3.Zero();
+            this._newPosition = BABYLON.Vector3.Zero();
+            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
+                if (collidedMesh === void 0) { collidedMesh = null; }
+                //TODO move this to the collision coordinator!
+                if (_this.getScene().workerCollisions)
+                    newPosition.multiplyInPlace(_this._collider.radius);
+                var updatePosition = function (newPos) {
+                    _this._newPosition.copyFrom(newPos);
+                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
+                    var oldPosition = _this.position.clone();
+                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
+                        _this.position.addInPlace(_this._diffPosition);
+                        if (_this.onCollide && collidedMesh) {
+                            _this.onCollide(collidedMesh);
+                        }
+                    }
+                };
+                updatePosition(newPosition);
+            };
+            this.inputs = new BABYLON.FreeCameraInputsManager(this);
+            this.inputs.addKeyboard().addMouse();
+        }
+        Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
+            //-- begin properties for backward compatibility for inputs
+            get: function () {
+                var mouse = this.inputs.attached["mouse"];
+                if (mouse)
+                    return mouse.angularSensibility;
+            },
+            set: function (value) {
+                var mouse = this.inputs.attached["mouse"];
+                if (mouse)
+                    mouse.angularSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FreeCamera.prototype, "keysUp", {
+            get: function () {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    return keyboard.keysUp;
+            },
+            set: function (value) {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    keyboard.keysUp = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FreeCamera.prototype, "keysDown", {
+            get: function () {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    return keyboard.keysDown;
+            },
+            set: function (value) {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    keyboard.keysDown = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FreeCamera.prototype, "keysLeft", {
+            get: function () {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    return keyboard.keysLeft;
+            },
+            set: function (value) {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    keyboard.keysLeft = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FreeCamera.prototype, "keysRight", {
+            get: function () {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    return keyboard.keysRight;
+            },
+            set: function (value) {
+                var keyboard = this.inputs.attached["keyboard"];
+                if (keyboard)
+                    keyboard.keysRight = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Controls
+        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            this.inputs.attachElement(element, noPreventDefault);
+        };
+        FreeCamera.prototype.detachControl = function (element) {
+            this.inputs.detachElement(element);
+            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
+            this.cameraRotation = new BABYLON.Vector2(0, 0);
+        };
+        FreeCamera.prototype._collideWithWorld = function (velocity) {
+            var globalPosition;
+            if (this.parent) {
+                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
+            }
+            else {
+                globalPosition = this.position;
+            }
+            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
+            this._collider.radius = this.ellipsoid;
+            //no need for clone, as long as gravity is not on.
+            var actualVelocity = velocity;
+            //add gravity to the velocity to prevent the dual-collision checking
+            if (this.applyGravity) {
+                //this prevents mending with cameraDirection, a global variable of the free camera class.
+                actualVelocity = velocity.add(this.getScene().gravity);
+            }
+            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
+        };
+        FreeCamera.prototype._checkInputs = function () {
+            if (!this._localDirection) {
+                this._localDirection = BABYLON.Vector3.Zero();
+                this._transformedDirection = BABYLON.Vector3.Zero();
+            }
+            this.inputs.checkInputs();
+            _super.prototype._checkInputs.call(this);
+        };
+        FreeCamera.prototype._decideIfNeedsToMove = function () {
+            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+        };
+        FreeCamera.prototype._updatePosition = function () {
+            if (this.checkCollisions && this.getScene().collisionsEnabled) {
+                this._collideWithWorld(this.cameraDirection);
+            }
+            else {
+                this.position.addInPlace(this.cameraDirection);
+            }
+        };
+        FreeCamera.prototype.dispose = function () {
+            this.inputs.clear();
+            _super.prototype.dispose.call(this);
+        };
+        FreeCamera.prototype.getTypeName = function () {
+            return "FreeCamera";
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], FreeCamera.prototype, "ellipsoid", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCamera.prototype, "checkCollisions", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCamera.prototype, "applyGravity", void 0);
+        return FreeCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.FreeCamera = FreeCamera;
+})(BABYLON || (BABYLON = {}));

+ 45 - 46
src/Cameras/babylon.freeCameraInputsManager.js

@@ -1,46 +1,45 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCameraInputsManager = (function (_super) {
-        __extends(FreeCameraInputsManager, _super);
-        function FreeCameraInputsManager(camera) {
-            _super.call(this, camera);
-        }
-        FreeCameraInputsManager.prototype.addKeyboard = function () {
-            this.add(new BABYLON.FreeCameraKeyboardMoveInput());
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
-            if (touchEnabled === void 0) { touchEnabled = true; }
-            this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addGamepad = function () {
-            this.add(new BABYLON.FreeCameraGamepadInput());
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
-            this.add(new BABYLON.FreeCameraDeviceOrientationInput());
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
-            this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addTouch = function () {
-            this.add(new BABYLON.FreeCameraTouchInput());
-            return this;
-        };
-        FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
-            this.add(new BABYLON.FreeCameraVirtualJoystickInput());
-            return this;
-        };
-        return FreeCameraInputsManager;
-    }(BABYLON.CameraInputsManager));
-    BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.freeCameraInputsManager.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCameraInputsManager = (function (_super) {
+        __extends(FreeCameraInputsManager, _super);
+        function FreeCameraInputsManager(camera) {
+            _super.call(this, camera);
+        }
+        FreeCameraInputsManager.prototype.addKeyboard = function () {
+            this.add(new BABYLON.FreeCameraKeyboardMoveInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
+            if (touchEnabled === void 0) { touchEnabled = true; }
+            this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addGamepad = function () {
+            this.add(new BABYLON.FreeCameraGamepadInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
+            this.add(new BABYLON.FreeCameraDeviceOrientationInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
+            this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addTouch = function () {
+            this.add(new BABYLON.FreeCameraTouchInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
+            this.add(new BABYLON.FreeCameraVirtualJoystickInput());
+            return this;
+        };
+        return FreeCameraInputsManager;
+    })(BABYLON.CameraInputsManager);
+    BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
+})(BABYLON || (BABYLON = {}));

+ 51 - 52
src/Cameras/babylon.gamepadCamera.js

@@ -1,52 +1,51 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var GamepadCamera = (function (_super) {
-        __extends(GamepadCamera, _super);
-        //-- end properties for backward compatibility for inputs
-        function GamepadCamera(name, position, scene) {
-            BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
-            _super.call(this, name, position, scene);
-        }
-        Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
-            //-- Begin properties for backward compatibility for inputs
-            get: function () {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    return gamepad.gamepadAngularSensibility;
-            },
-            set: function (value) {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    gamepad.gamepadAngularSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
-            get: function () {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    return gamepad.gamepadMoveSensibility;
-            },
-            set: function (value) {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    gamepad.gamepadMoveSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        GamepadCamera.prototype.getTypeName = function () {
-            return "GamepadCamera";
-        };
-        return GamepadCamera;
-    }(BABYLON.UniversalCamera));
-    BABYLON.GamepadCamera = GamepadCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.gamepadCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var GamepadCamera = (function (_super) {
+        __extends(GamepadCamera, _super);
+        //-- end properties for backward compatibility for inputs
+        function GamepadCamera(name, position, scene) {
+            BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
+            _super.call(this, name, position, scene);
+        }
+        Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
+            //-- Begin properties for backward compatibility for inputs
+            get: function () {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    return gamepad.gamepadAngularSensibility;
+            },
+            set: function (value) {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    gamepad.gamepadAngularSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
+            get: function () {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    return gamepad.gamepadMoveSensibility;
+            },
+            set: function (value) {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    gamepad.gamepadMoveSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        GamepadCamera.prototype.getTypeName = function () {
+            return "GamepadCamera";
+        };
+        return GamepadCamera;
+    })(BABYLON.UniversalCamera);
+    BABYLON.GamepadCamera = GamepadCamera;
+})(BABYLON || (BABYLON = {}));

+ 116 - 117
src/Cameras/babylon.stereoscopicCameras.js

@@ -1,117 +1,116 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var AnaglyphFreeCamera = (function (_super) {
-        __extends(AnaglyphFreeCamera, _super);
-        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        AnaglyphFreeCamera.prototype.getTypeName = function () {
-            return "AnaglyphFreeCamera";
-        };
-        return AnaglyphFreeCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
-    var AnaglyphArcRotateCamera = (function (_super) {
-        __extends(AnaglyphArcRotateCamera, _super);
-        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
-            _super.call(this, name, alpha, beta, radius, target, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        AnaglyphArcRotateCamera.prototype.getTypeName = function () {
-            return "AnaglyphArcRotateCamera";
-        };
-        return AnaglyphArcRotateCamera;
-    }(BABYLON.ArcRotateCamera));
-    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
-    var AnaglyphGamepadCamera = (function (_super) {
-        __extends(AnaglyphGamepadCamera, _super);
-        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        AnaglyphGamepadCamera.prototype.getTypeName = function () {
-            return "AnaglyphGamepadCamera";
-        };
-        return AnaglyphGamepadCamera;
-    }(BABYLON.GamepadCamera));
-    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
-    var AnaglyphUniversalCamera = (function (_super) {
-        __extends(AnaglyphUniversalCamera, _super);
-        function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        AnaglyphUniversalCamera.prototype.getTypeName = function () {
-            return "AnaglyphUniversalCamera";
-        };
-        return AnaglyphUniversalCamera;
-    }(BABYLON.UniversalCamera));
-    BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
-    var StereoscopicFreeCamera = (function (_super) {
-        __extends(StereoscopicFreeCamera, _super);
-        function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
-            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        StereoscopicFreeCamera.prototype.getTypeName = function () {
-            return "StereoscopicFreeCamera";
-        };
-        return StereoscopicFreeCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
-    var StereoscopicArcRotateCamera = (function (_super) {
-        __extends(StereoscopicArcRotateCamera, _super);
-        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
-            _super.call(this, name, alpha, beta, radius, target, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
-            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        StereoscopicArcRotateCamera.prototype.getTypeName = function () {
-            return "StereoscopicArcRotateCamera";
-        };
-        return StereoscopicArcRotateCamera;
-    }(BABYLON.ArcRotateCamera));
-    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
-    var StereoscopicGamepadCamera = (function (_super) {
-        __extends(StereoscopicGamepadCamera, _super);
-        function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
-            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        StereoscopicGamepadCamera.prototype.getTypeName = function () {
-            return "StereoscopicGamepadCamera";
-        };
-        return StereoscopicGamepadCamera;
-    }(BABYLON.GamepadCamera));
-    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
-    var StereoscopicUniversalCamera = (function (_super) {
-        __extends(StereoscopicUniversalCamera, _super);
-        function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
-            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        StereoscopicUniversalCamera.prototype.getTypeName = function () {
-            return "StereoscopicUniversalCamera";
-        };
-        return StereoscopicUniversalCamera;
-    }(BABYLON.UniversalCamera));
-    BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.stereoscopicCameras.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var AnaglyphFreeCamera = (function (_super) {
+        __extends(AnaglyphFreeCamera, _super);
+        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        AnaglyphFreeCamera.prototype.getTypeName = function () {
+            return "AnaglyphFreeCamera";
+        };
+        return AnaglyphFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
+    var AnaglyphArcRotateCamera = (function (_super) {
+        __extends(AnaglyphArcRotateCamera, _super);
+        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
+            _super.call(this, name, alpha, beta, radius, target, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        AnaglyphArcRotateCamera.prototype.getTypeName = function () {
+            return "AnaglyphArcRotateCamera";
+        };
+        return AnaglyphArcRotateCamera;
+    })(BABYLON.ArcRotateCamera);
+    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
+    var AnaglyphGamepadCamera = (function (_super) {
+        __extends(AnaglyphGamepadCamera, _super);
+        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        AnaglyphGamepadCamera.prototype.getTypeName = function () {
+            return "AnaglyphGamepadCamera";
+        };
+        return AnaglyphGamepadCamera;
+    })(BABYLON.GamepadCamera);
+    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
+    var AnaglyphUniversalCamera = (function (_super) {
+        __extends(AnaglyphUniversalCamera, _super);
+        function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        AnaglyphUniversalCamera.prototype.getTypeName = function () {
+            return "AnaglyphUniversalCamera";
+        };
+        return AnaglyphUniversalCamera;
+    })(BABYLON.UniversalCamera);
+    BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
+    var StereoscopicFreeCamera = (function (_super) {
+        __extends(StereoscopicFreeCamera, _super);
+        function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
+            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        StereoscopicFreeCamera.prototype.getTypeName = function () {
+            return "StereoscopicFreeCamera";
+        };
+        return StereoscopicFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
+    var StereoscopicArcRotateCamera = (function (_super) {
+        __extends(StereoscopicArcRotateCamera, _super);
+        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
+            _super.call(this, name, alpha, beta, radius, target, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
+            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        StereoscopicArcRotateCamera.prototype.getTypeName = function () {
+            return "StereoscopicArcRotateCamera";
+        };
+        return StereoscopicArcRotateCamera;
+    })(BABYLON.ArcRotateCamera);
+    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
+    var StereoscopicGamepadCamera = (function (_super) {
+        __extends(StereoscopicGamepadCamera, _super);
+        function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
+            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        StereoscopicGamepadCamera.prototype.getTypeName = function () {
+            return "StereoscopicGamepadCamera";
+        };
+        return StereoscopicGamepadCamera;
+    })(BABYLON.GamepadCamera);
+    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
+    var StereoscopicUniversalCamera = (function (_super) {
+        __extends(StereoscopicUniversalCamera, _super);
+        function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
+            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        StereoscopicUniversalCamera.prototype.getTypeName = function () {
+            return "StereoscopicUniversalCamera";
+        };
+        return StereoscopicUniversalCamera;
+    })(BABYLON.UniversalCamera);
+    BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
+})(BABYLON || (BABYLON = {}));

+ 58 - 59
src/Cameras/babylon.touchCamera.js

@@ -1,59 +1,58 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var TouchCamera = (function (_super) {
-        __extends(TouchCamera, _super);
-        //-- end properties for backward compatibility for inputs
-        function TouchCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.inputs.addTouch();
-            this._setupInputs();
-        }
-        Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
-            //-- Begin properties for backward compatibility for inputs
-            get: function () {
-                var touch = this.inputs.attached["touch"];
-                if (touch)
-                    return touch.touchAngularSensibility;
-            },
-            set: function (value) {
-                var touch = this.inputs.attached["touch"];
-                if (touch)
-                    touch.touchAngularSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
-            get: function () {
-                var touch = this.inputs.attached["touch"];
-                if (touch)
-                    return touch.touchMoveSensibility;
-            },
-            set: function (value) {
-                var touch = this.inputs.attached["touch"];
-                if (touch)
-                    touch.touchMoveSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        TouchCamera.prototype.getTypeName = function () {
-            return "TouchCamera";
-        };
-        TouchCamera.prototype._setupInputs = function () {
-            var mouse = this.inputs.attached["mouse"];
-            if (mouse) {
-                mouse.touchEnabled = false;
-            }
-        };
-        return TouchCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.TouchCamera = TouchCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.touchCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var TouchCamera = (function (_super) {
+        __extends(TouchCamera, _super);
+        //-- end properties for backward compatibility for inputs
+        function TouchCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addTouch();
+            this._setupInputs();
+        }
+        Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
+            //-- Begin properties for backward compatibility for inputs
+            get: function () {
+                var touch = this.inputs.attached["touch"];
+                if (touch)
+                    return touch.touchAngularSensibility;
+            },
+            set: function (value) {
+                var touch = this.inputs.attached["touch"];
+                if (touch)
+                    touch.touchAngularSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
+            get: function () {
+                var touch = this.inputs.attached["touch"];
+                if (touch)
+                    return touch.touchMoveSensibility;
+            },
+            set: function (value) {
+                var touch = this.inputs.attached["touch"];
+                if (touch)
+                    touch.touchMoveSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        TouchCamera.prototype.getTypeName = function () {
+            return "TouchCamera";
+        };
+        TouchCamera.prototype._setupInputs = function () {
+            var mouse = this.inputs.attached["mouse"];
+            if (mouse) {
+                mouse.touchEnabled = false;
+            }
+        };
+        return TouchCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.TouchCamera = TouchCamera;
+})(BABYLON || (BABYLON = {}));

+ 51 - 52
src/Cameras/babylon.universalCamera.js

@@ -1,52 +1,51 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var UniversalCamera = (function (_super) {
-        __extends(UniversalCamera, _super);
-        //-- end properties for backward compatibility for inputs
-        function UniversalCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.inputs.addGamepad();
-        }
-        Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
-            //-- Begin properties for backward compatibility for inputs
-            get: function () {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    return gamepad.gamepadAngularSensibility;
-            },
-            set: function (value) {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    gamepad.gamepadAngularSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
-            get: function () {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    return gamepad.gamepadMoveSensibility;
-            },
-            set: function (value) {
-                var gamepad = this.inputs.attached["gamepad"];
-                if (gamepad)
-                    gamepad.gamepadMoveSensibility = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        UniversalCamera.prototype.getTypeName = function () {
-            return "UniversalCamera";
-        };
-        return UniversalCamera;
-    }(BABYLON.TouchCamera));
-    BABYLON.UniversalCamera = UniversalCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.universalCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var UniversalCamera = (function (_super) {
+        __extends(UniversalCamera, _super);
+        //-- end properties for backward compatibility for inputs
+        function UniversalCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addGamepad();
+        }
+        Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
+            //-- Begin properties for backward compatibility for inputs
+            get: function () {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    return gamepad.gamepadAngularSensibility;
+            },
+            set: function (value) {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    gamepad.gamepadAngularSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
+            get: function () {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    return gamepad.gamepadMoveSensibility;
+            },
+            set: function (value) {
+                var gamepad = this.inputs.attached["gamepad"];
+                if (gamepad)
+                    gamepad.gamepadMoveSensibility = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        UniversalCamera.prototype.getTypeName = function () {
+            return "UniversalCamera";
+        };
+        return UniversalCamera;
+    })(BABYLON.TouchCamera);
+    BABYLON.UniversalCamera = UniversalCamera;
+})(BABYLON || (BABYLON = {}));

+ 18 - 19
src/Cameras/babylon.virtualJoysticksCamera.js

@@ -1,19 +1,18 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var VirtualJoysticksCamera = (function (_super) {
-        __extends(VirtualJoysticksCamera, _super);
-        function VirtualJoysticksCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.inputs.addVirtualJoystick();
-        }
-        return VirtualJoysticksCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var VirtualJoysticksCamera = (function (_super) {
+        __extends(VirtualJoysticksCamera, _super);
+        function VirtualJoysticksCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addVirtualJoystick();
+        }
+        return VirtualJoysticksCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
+})(BABYLON || (BABYLON = {}));

+ 157 - 158
src/Canvas2d/babylon.bounding2d.js

@@ -1,158 +1,157 @@
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * Stores 2D Bounding Information.
-     * This class handles a circle area and a bounding rectangle one.
-     */
-    var BoundingInfo2D = (function () {
-        function BoundingInfo2D() {
-            this.radius = 0;
-            this.center = BABYLON.Vector2.Zero();
-            this.extent = BABYLON.Vector2.Zero();
-        }
-        BoundingInfo2D.CreateFromSize = function (size, origin) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
-            return r;
-        };
-        BoundingInfo2D.CreateFromRadius = function (radius, origin) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
-            return r;
-        };
-        BoundingInfo2D.CreateFromPoints = function (points, origin) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
-            return r;
-        };
-        BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
-            b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
-            b.extent = b.center.clone();
-            if (origin) {
-                b.center.x -= size.width * origin.x;
-                b.center.y -= size.height * origin.y;
-            }
-            b.radius = b.extent.length();
-        };
-        BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
-            b.center = BABYLON.Vector2.Zero();
-            if (origin) {
-                b.center.x -= radius * origin.x;
-                b.center.y -= radius * origin.y;
-            }
-            b.extent = new BABYLON.Vector2(radius, radius);
-            b.radius = radius;
-        };
-        BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
-            var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
-            for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
-                var p = points_1[_i];
-                xmin = Math.min(p.x, xmin);
-                xmax = Math.max(p.x, xmax);
-                ymin = Math.min(p.y, ymin);
-                ymax = Math.max(p.y, ymax);
-            }
-            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
-        };
-        BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
-            var w = xmax - xmin;
-            var h = ymax - ymin;
-            b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
-            if (origin) {
-                b.center.x -= w * origin.x;
-                b.center.y -= h * origin.y;
-            }
-            b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
-            b.radius = b.extent.length();
-        };
-        /**
-         * Duplicate this instance and return a new one
-         * @return the duplicated instance
-         */
-        BoundingInfo2D.prototype.clone = function () {
-            var r = new BoundingInfo2D();
-            r.center = this.center.clone();
-            r.radius = this.radius;
-            r.extent = this.extent.clone();
-            return r;
-        };
-        BoundingInfo2D.prototype.max = function () {
-            var r = BABYLON.Vector2.Zero();
-            this.maxToRef(r);
-            return r;
-        };
-        BoundingInfo2D.prototype.maxToRef = function (result) {
-            result.x = this.center.x + this.extent.x;
-            result.y = this.center.y + this.extent.y;
-        };
-        /**
-         * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
-         * @param matrix the transformation matrix to apply
-         * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
-         */
-        BoundingInfo2D.prototype.transform = function (matrix) {
-            var r = new BoundingInfo2D();
-            this.transformToRef(matrix, r);
-            return r;
-        };
-        /**
-         * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
-         * @param other the second BoundingInfo2D to compute the union with this one
-         * @return a new instance containing the result of the union
-         */
-        BoundingInfo2D.prototype.union = function (other) {
-            var r = new BoundingInfo2D();
-            this.unionToRef(other, r);
-            return r;
-        };
-        /**
-         * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
-         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
-         * @param matrix The matrix to use to compute the transformation
-         * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
-         */
-        BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
-            // Construct a bounding box based on the extent values
-            var p = BoundingInfo2D._transform;
-            p[0].x = this.center.x + this.extent.x;
-            p[0].y = this.center.y + this.extent.y;
-            p[1].x = this.center.x + this.extent.x;
-            p[1].y = this.center.y - this.extent.y;
-            p[2].x = this.center.x - this.extent.x;
-            p[2].y = this.center.y - this.extent.y;
-            p[3].x = this.center.x - this.extent.x;
-            p[3].y = this.center.y + this.extent.y;
-            // Transform the four points of the bounding box with the matrix
-            for (var i = 0; i < 4; i++) {
-                BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
-            }
-            BoundingInfo2D.CreateFromPointsToRef(p, result);
-        };
-        /**
-         * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
-         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
-         * @param other the second object used to compute the union
-         * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
-         */
-        BoundingInfo2D.prototype.unionToRef = function (other, result) {
-            var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
-            var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
-            var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
-            var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
-            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
-        };
-        BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
-            // is it inside the radius?
-            var pickLocal = pickPosition.subtract(this.center);
-            if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
-                // is it inside the rectangle?
-                return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
-            }
-            return false;
-        };
-        BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
-        return BoundingInfo2D;
-    }());
-    BABYLON.BoundingInfo2D = BoundingInfo2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.bounding2d.js.map
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Stores 2D Bounding Information.
+     * This class handles a circle area and a bounding rectangle one.
+     */
+    var BoundingInfo2D = (function () {
+        function BoundingInfo2D() {
+            this.radius = 0;
+            this.center = BABYLON.Vector2.Zero();
+            this.extent = BABYLON.Vector2.Zero();
+        }
+        BoundingInfo2D.CreateFromSize = function (size, origin) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
+            return r;
+        };
+        BoundingInfo2D.CreateFromRadius = function (radius, origin) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
+            return r;
+        };
+        BoundingInfo2D.CreateFromPoints = function (points, origin) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
+            return r;
+        };
+        BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
+            b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
+            b.extent = b.center.clone();
+            if (origin) {
+                b.center.x -= size.width * origin.x;
+                b.center.y -= size.height * origin.y;
+            }
+            b.radius = b.extent.length();
+        };
+        BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
+            b.center = BABYLON.Vector2.Zero();
+            if (origin) {
+                b.center.x -= radius * origin.x;
+                b.center.y -= radius * origin.y;
+            }
+            b.extent = new BABYLON.Vector2(radius, radius);
+            b.radius = radius;
+        };
+        BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
+            var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
+            for (var _i = 0; _i < points.length; _i++) {
+                var p = points[_i];
+                xmin = Math.min(p.x, xmin);
+                xmax = Math.max(p.x, xmax);
+                ymin = Math.min(p.y, ymin);
+                ymax = Math.max(p.y, ymax);
+            }
+            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
+        };
+        BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
+            var w = xmax - xmin;
+            var h = ymax - ymin;
+            b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
+            if (origin) {
+                b.center.x -= w * origin.x;
+                b.center.y -= h * origin.y;
+            }
+            b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
+            b.radius = b.extent.length();
+        };
+        /**
+         * Duplicate this instance and return a new one
+         * @return the duplicated instance
+         */
+        BoundingInfo2D.prototype.clone = function () {
+            var r = new BoundingInfo2D();
+            r.center = this.center.clone();
+            r.radius = this.radius;
+            r.extent = this.extent.clone();
+            return r;
+        };
+        BoundingInfo2D.prototype.max = function () {
+            var r = BABYLON.Vector2.Zero();
+            this.maxToRef(r);
+            return r;
+        };
+        BoundingInfo2D.prototype.maxToRef = function (result) {
+            result.x = this.center.x + this.extent.x;
+            result.y = this.center.y + this.extent.y;
+        };
+        /**
+         * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
+         * @param matrix the transformation matrix to apply
+         * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
+         */
+        BoundingInfo2D.prototype.transform = function (matrix) {
+            var r = new BoundingInfo2D();
+            this.transformToRef(matrix, r);
+            return r;
+        };
+        /**
+         * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
+         * @param other the second BoundingInfo2D to compute the union with this one
+         * @return a new instance containing the result of the union
+         */
+        BoundingInfo2D.prototype.union = function (other) {
+            var r = new BoundingInfo2D();
+            this.unionToRef(other, r);
+            return r;
+        };
+        /**
+         * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
+         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
+         * @param matrix The matrix to use to compute the transformation
+         * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
+         */
+        BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
+            // Construct a bounding box based on the extent values
+            var p = BoundingInfo2D._transform;
+            p[0].x = this.center.x + this.extent.x;
+            p[0].y = this.center.y + this.extent.y;
+            p[1].x = this.center.x + this.extent.x;
+            p[1].y = this.center.y - this.extent.y;
+            p[2].x = this.center.x - this.extent.x;
+            p[2].y = this.center.y - this.extent.y;
+            p[3].x = this.center.x - this.extent.x;
+            p[3].y = this.center.y + this.extent.y;
+            // Transform the four points of the bounding box with the matrix
+            for (var i = 0; i < 4; i++) {
+                BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
+            }
+            BoundingInfo2D.CreateFromPointsToRef(p, result);
+        };
+        /**
+         * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
+         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
+         * @param other the second object used to compute the union
+         * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
+         */
+        BoundingInfo2D.prototype.unionToRef = function (other, result) {
+            var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
+            var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
+            var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
+            var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
+            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
+        };
+        BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
+            // is it inside the radius?
+            var pickLocal = pickPosition.subtract(this.center);
+            if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
+                // is it inside the rectangle?
+                return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
+            }
+            return false;
+        };
+        BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
+        return BoundingInfo2D;
+    })();
+    BABYLON.BoundingInfo2D = BoundingInfo2D;
+})(BABYLON || (BABYLON = {}));

+ 184 - 185
src/Canvas2d/babylon.brushes2d.js

@@ -1,185 +1,184 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * Base class implementing the ILocable interface.
-     * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
-     */
-    var LockableBase = (function () {
-        function LockableBase() {
-        }
-        LockableBase.prototype.isLocked = function () {
-            return this._isLocked;
-        };
-        LockableBase.prototype.lock = function () {
-            if (this._isLocked) {
-                return true;
-            }
-            this.onLock();
-            this._isLocked = true;
-            return false;
-        };
-        /**
-         * Protected handler that will be called when the instance is about to be locked.
-         */
-        LockableBase.prototype.onLock = function () {
-        };
-        return LockableBase;
-    }());
-    BABYLON.LockableBase = LockableBase;
-    /**
-     * This class implements a Brush that will be drawn with a uniform solid color (i.e. the same color everywhere in the content where the brush is assigned to).
-     */
-    var SolidColorBrush2D = (function (_super) {
-        __extends(SolidColorBrush2D, _super);
-        function SolidColorBrush2D(color, lock) {
-            if (lock === void 0) { lock = false; }
-            _super.call(this);
-            this._color = color;
-            if (lock) {
-                {
-                    this.lock();
-                }
-            }
-        }
-        SolidColorBrush2D.prototype.isTransparent = function () {
-            return this._color && this._color.a < 1.0;
-        };
-        Object.defineProperty(SolidColorBrush2D.prototype, "color", {
-            /**
-             * The color used by this instance to render
-             * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
-             */
-            get: function () {
-                return this._color;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
-         */
-        SolidColorBrush2D.prototype.toString = function () {
-            return this._color.toHexString();
-        };
-        SolidColorBrush2D = __decorate([
-            BABYLON.className("SolidColorBrush2D")
-        ], SolidColorBrush2D);
-        return SolidColorBrush2D;
-    }(LockableBase));
-    BABYLON.SolidColorBrush2D = SolidColorBrush2D;
-    var GradientColorBrush2D = (function (_super) {
-        __extends(GradientColorBrush2D, _super);
-        function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
-            if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
-            if (rotation === void 0) { rotation = 0; }
-            if (scale === void 0) { scale = 1; }
-            if (lock === void 0) { lock = false; }
-            _super.call(this);
-            this._color1 = color1;
-            this._color2 = color2;
-            this._translation = translation;
-            this._rotation = rotation;
-            this._scale = scale;
-            if (lock) {
-                this.lock();
-            }
-        }
-        GradientColorBrush2D.prototype.isTransparent = function () {
-            return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
-        };
-        Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
-            get: function () {
-                return this._color1;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color1 = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
-            get: function () {
-                return this._color2;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color2 = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
-            get: function () {
-                return this._translation;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._translation = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
-            get: function () {
-                return this._rotation;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._rotation = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
-            get: function () {
-                return this._scale;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._scale = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        GradientColorBrush2D.prototype.toString = function () {
-            return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
-        };
-        GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
-            return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
-        };
-        GradientColorBrush2D = __decorate([
-            BABYLON.className("GradientColorBrush2D")
-        ], GradientColorBrush2D);
-        return GradientColorBrush2D;
-    }(LockableBase));
-    BABYLON.GradientColorBrush2D = GradientColorBrush2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.brushes2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Base class implementing the ILocable interface.
+     * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
+     */
+    var LockableBase = (function () {
+        function LockableBase() {
+        }
+        LockableBase.prototype.isLocked = function () {
+            return this._isLocked;
+        };
+        LockableBase.prototype.lock = function () {
+            if (this._isLocked) {
+                return true;
+            }
+            this.onLock();
+            this._isLocked = true;
+            return false;
+        };
+        /**
+         * Protected handler that will be called when the instance is about to be locked.
+         */
+        LockableBase.prototype.onLock = function () {
+        };
+        return LockableBase;
+    })();
+    BABYLON.LockableBase = LockableBase;
+    /**
+     * This class implements a Brush that will be drawn with a uniform solid color (i.e. the same color everywhere in the content where the brush is assigned to).
+     */
+    var SolidColorBrush2D = (function (_super) {
+        __extends(SolidColorBrush2D, _super);
+        function SolidColorBrush2D(color, lock) {
+            if (lock === void 0) { lock = false; }
+            _super.call(this);
+            this._color = color;
+            if (lock) {
+                {
+                    this.lock();
+                }
+            }
+        }
+        SolidColorBrush2D.prototype.isTransparent = function () {
+            return this._color && this._color.a < 1.0;
+        };
+        Object.defineProperty(SolidColorBrush2D.prototype, "color", {
+            /**
+             * The color used by this instance to render
+             * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
+             */
+            get: function () {
+                return this._color;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
+         */
+        SolidColorBrush2D.prototype.toString = function () {
+            return this._color.toHexString();
+        };
+        SolidColorBrush2D = __decorate([
+            BABYLON.className("SolidColorBrush2D")
+        ], SolidColorBrush2D);
+        return SolidColorBrush2D;
+    })(LockableBase);
+    BABYLON.SolidColorBrush2D = SolidColorBrush2D;
+    var GradientColorBrush2D = (function (_super) {
+        __extends(GradientColorBrush2D, _super);
+        function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
+            if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
+            if (rotation === void 0) { rotation = 0; }
+            if (scale === void 0) { scale = 1; }
+            if (lock === void 0) { lock = false; }
+            _super.call(this);
+            this._color1 = color1;
+            this._color2 = color2;
+            this._translation = translation;
+            this._rotation = rotation;
+            this._scale = scale;
+            if (lock) {
+                this.lock();
+            }
+        }
+        GradientColorBrush2D.prototype.isTransparent = function () {
+            return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
+        };
+        Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
+            get: function () {
+                return this._color1;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color1 = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
+            get: function () {
+                return this._color2;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color2 = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
+            get: function () {
+                return this._translation;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._translation = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
+            get: function () {
+                return this._rotation;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._rotation = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
+            get: function () {
+                return this._scale;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._scale = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        GradientColorBrush2D.prototype.toString = function () {
+            return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
+        };
+        GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
+            return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
+        };
+        GradientColorBrush2D = __decorate([
+            BABYLON.className("GradientColorBrush2D")
+        ], GradientColorBrush2D);
+        return GradientColorBrush2D;
+    })(LockableBase);
+    BABYLON.GradientColorBrush2D = GradientColorBrush2D;
+})(BABYLON || (BABYLON = {}));

+ 351 - 331
src/Canvas2d/babylon.ellipse2d.js

@@ -1,331 +1,351 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Ellipse2DRenderCache = (function (_super) {
-        __extends(Ellipse2DRenderCache, _super);
-        function Ellipse2DRenderCache(engine, modelKey) {
-            _super.call(this, engine, modelKey);
-            this.effectsReady = false;
-            this.fillVB = null;
-            this.fillIB = null;
-            this.fillIndicesCount = 0;
-            this.instancingFillAttributes = null;
-            this.effectFillInstanced = null;
-            this.effectFill = null;
-            this.borderVB = null;
-            this.borderIB = null;
-            this.borderIndicesCount = 0;
-            this.instancingBorderAttributes = null;
-            this.effectBorderInstanced = null;
-            this.effectBorder = null;
-        }
-        Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
-                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            var engine = instanceInfo.owner.owner.engine;
-            var depthFunction = 0;
-            if (this.effectFill && this.effectBorder) {
-                depthFunction = engine.getDepthFunction();
-                engine.setDepthFunctionToLessOrEqual();
-            }
-            var curAlphaMode = engine.getAlphaMode();
-            if (this.effectFill) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-                }
-                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingFillAttributes) {
-                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
-                    }
-                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
-                    engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.fillIndicesCount);
-                    }
-                }
-            }
-            if (this.effectBorder) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-                }
-                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingBorderAttributes) {
-                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
-                    }
-                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
-                    engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.borderIndicesCount);
-                    }
-                }
-            }
-            engine.setAlphaMode(curAlphaMode);
-            if (this.effectFill && this.effectBorder) {
-                engine.setDepthFunction(depthFunction);
-            }
-            return true;
-        };
-        Ellipse2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.fillVB) {
-                this._engine._releaseBuffer(this.fillVB);
-                this.fillVB = null;
-            }
-            if (this.fillIB) {
-                this._engine._releaseBuffer(this.fillIB);
-                this.fillIB = null;
-            }
-            if (this.effectFill) {
-                this._engine._releaseEffect(this.effectFill);
-                this.effectFill = null;
-            }
-            if (this.effectFillInstanced) {
-                this._engine._releaseEffect(this.effectFillInstanced);
-                this.effectFillInstanced = null;
-            }
-            if (this.borderVB) {
-                this._engine._releaseBuffer(this.borderVB);
-                this.borderVB = null;
-            }
-            if (this.borderIB) {
-                this._engine._releaseBuffer(this.borderIB);
-                this.borderIB = null;
-            }
-            if (this.effectBorder) {
-                this._engine._releaseEffect(this.effectBorder);
-                this.effectBorder = null;
-            }
-            if (this.effectBorderInstanced) {
-                this._engine._releaseEffect(this.effectBorderInstanced);
-                this.effectBorderInstanced = null;
-            }
-            return true;
-        };
-        return Ellipse2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
-    var Ellipse2DInstanceData = (function (_super) {
-        __extends(Ellipse2DInstanceData, _super);
-        function Ellipse2DInstanceData(partId) {
-            _super.call(this, partId, 1);
-        }
-        Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Ellipse2DInstanceData.prototype, "properties", null);
-        return Ellipse2DInstanceData;
-    }(BABYLON.Shape2DInstanceData));
-    BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
-    var Ellipse2D = (function (_super) {
-        __extends(Ellipse2D, _super);
-        /**
-         * Create an Ellipse 2D Shape primitive
-         * @param parent the parent primitive, must be a valid primitive (or the Canvas)
-         * options:
-         *  - id: a text identifier, for information purpose
-         *  - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
-         *  - origin: define the normalized origin point location, default [0.5;0.5]
-         *  - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
-         *  - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
-         *  - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
-         *  - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
-         *  - borderThickness: the thickness of the drawn border, default is 1.
-         *  - isVisible: true if the primitive must be visible, false for hidden. Default is true.
-         *  - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
-         *  - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
-         *  - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
-         */
-        function Ellipse2D(settings) {
-            // Avoid checking every time if the object exists
-            if (settings == null) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            var size = settings.size || (new BABYLON.Size(settings.width || 10, settings.height || 10));
-            var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
-            this.size = size;
-            this.subdivisions = sub;
-        }
-        Object.defineProperty(Ellipse2D.prototype, "actualSize", {
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this._size;
-            },
-            set: function (value) {
-                this._actualSize = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
-            get: function () {
-                return this._subdivisions;
-            },
-            set: function (value) {
-                this._subdivisions = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
-            var w = this.size.width / 2;
-            var h = this.size.height / 2;
-            var x = intersectInfo._localPickPosition.x - w;
-            var y = intersectInfo._localPickPosition.y - h;
-            return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
-        };
-        Ellipse2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
-        };
-        Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            // Need to create WebGL resources for fill part?
-            if (this.fill) {
-                var vbSize = this.subdivisions + 1;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.fillVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize - 1;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < triCount; i++) {
-                    ib[i * 3 + 0] = 0;
-                    ib[i * 3 + 2] = i + 1;
-                    ib[i * 3 + 1] = i + 2;
-                }
-                ib[triCount * 3 - 2] = 1;
-                renderCache.fillIB = engine.createIndexBuffer(ib);
-                renderCache.fillIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
-                if (ei) {
-                    renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
-                renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            // Need to create WebGL resource for border part?
-            if (this.border) {
-                var vbSize = this.subdivisions * 2;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.borderVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize;
-                var rs = triCount / 2;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < rs; i++) {
-                    var r0 = i;
-                    var r1 = (i + 1) % rs;
-                    ib[i * 6 + 0] = rs + r1;
-                    ib[i * 6 + 1] = rs + r0;
-                    ib[i * 6 + 2] = r0;
-                    ib[i * 6 + 3] = r1;
-                    ib[i * 6 + 4] = rs + r1;
-                    ib[i * 6 + 5] = r0;
-                }
-                renderCache.borderIB = engine.createIndexBuffer(ib);
-                renderCache.borderIndicesCount = (triCount * 3);
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
-                if (ei) {
-                    renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
-                renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            return renderCache;
-        };
-        Ellipse2D.prototype.createInstanceDataParts = function () {
-            var res = new Array();
-            if (this.border) {
-                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
-            }
-            if (this.fill) {
-                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
-            }
-            return res;
-        };
-        Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
-            }
-            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
-            }
-            return true;
-        };
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
-        ], Ellipse2D.prototype, "actualSize", null);
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
-        ], Ellipse2D.prototype, "subdivisions", null);
-        Ellipse2D = __decorate([
-            BABYLON.className("Ellipse2D")
-        ], Ellipse2D);
-        return Ellipse2D;
-    }(BABYLON.Shape2D));
-    BABYLON.Ellipse2D = Ellipse2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.ellipse2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Ellipse2DRenderCache = (function (_super) {
+        __extends(Ellipse2DRenderCache, _super);
+        function Ellipse2DRenderCache(engine, modelKey) {
+            _super.call(this, engine, modelKey);
+            this.effectsReady = false;
+            this.fillVB = null;
+            this.fillIB = null;
+            this.fillIndicesCount = 0;
+            this.instancingFillAttributes = null;
+            this.effectFillInstanced = null;
+            this.effectFill = null;
+            this.borderVB = null;
+            this.borderIB = null;
+            this.borderIndicesCount = 0;
+            this.instancingBorderAttributes = null;
+            this.effectBorderInstanced = null;
+            this.effectBorder = null;
+        }
+        Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
+                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            var engine = instanceInfo.owner.owner.engine;
+            var depthFunction = 0;
+            if (this.effectFill && this.effectBorder) {
+                depthFunction = engine.getDepthFunction();
+                engine.setDepthFunctionToLessOrEqual();
+            }
+            var curAlphaMode = engine.getAlphaMode();
+            if (this.effectFill) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+                }
+                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingFillAttributes) {
+                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
+                    }
+                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
+                    engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.fillIndicesCount);
+                    }
+                }
+            }
+            if (this.effectBorder) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+                }
+                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingBorderAttributes) {
+                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
+                    }
+                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
+                    engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.borderIndicesCount);
+                    }
+                }
+            }
+            engine.setAlphaMode(curAlphaMode);
+            if (this.effectFill && this.effectBorder) {
+                engine.setDepthFunction(depthFunction);
+            }
+            return true;
+        };
+        Ellipse2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.fillVB) {
+                this._engine._releaseBuffer(this.fillVB);
+                this.fillVB = null;
+            }
+            if (this.fillIB) {
+                this._engine._releaseBuffer(this.fillIB);
+                this.fillIB = null;
+            }
+            if (this.effectFill) {
+                this._engine._releaseEffect(this.effectFill);
+                this.effectFill = null;
+            }
+            if (this.effectFillInstanced) {
+                this._engine._releaseEffect(this.effectFillInstanced);
+                this.effectFillInstanced = null;
+            }
+            if (this.borderVB) {
+                this._engine._releaseBuffer(this.borderVB);
+                this.borderVB = null;
+            }
+            if (this.borderIB) {
+                this._engine._releaseBuffer(this.borderIB);
+                this.borderIB = null;
+            }
+            if (this.effectBorder) {
+                this._engine._releaseEffect(this.effectBorder);
+                this.effectBorder = null;
+            }
+            if (this.effectBorderInstanced) {
+                this._engine._releaseEffect(this.effectBorderInstanced);
+                this.effectBorderInstanced = null;
+            }
+            return true;
+        };
+        return Ellipse2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
+    var Ellipse2DInstanceData = (function (_super) {
+        __extends(Ellipse2DInstanceData, _super);
+        function Ellipse2DInstanceData(partId) {
+            _super.call(this, partId, 1);
+        }
+        Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Ellipse2DInstanceData.prototype, "properties", null);
+        return Ellipse2DInstanceData;
+    })(BABYLON.Shape2DInstanceData);
+    BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
+    var Ellipse2D = (function (_super) {
+        __extends(Ellipse2D, _super);
+        function Ellipse2D() {
+            _super.apply(this, arguments);
+        }
+        Object.defineProperty(Ellipse2D.prototype, "actualSize", {
+            get: function () {
+                return this.size;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Ellipse2D.prototype, "size", {
+            get: function () {
+                return this._size;
+            },
+            set: function (value) {
+                this._size = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
+            get: function () {
+                return this._subdivisions;
+            },
+            set: function (value) {
+                this._subdivisions = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
+            var x = intersectInfo._localPickPosition.x;
+            var y = intersectInfo._localPickPosition.y;
+            var w = this.size.width / 2;
+            var h = this.size.height / 2;
+            return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
+        };
+        Ellipse2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
+        };
+        Ellipse2D.prototype.setupEllipse2D = function (owner, parent, id, position, origin, size, subdivisions, fill, border, borderThickness, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
+            this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
+            this.size = size;
+            this.subdivisions = subdivisions;
+        };
+        /**
+         * Create an Ellipse 2D Shape primitive
+         * @param parent the parent primitive, must be a valid primitive (or the Canvas)
+         * options:
+         *  - id: a text identifier, for information purpose
+         *  - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
+         *  - origin: define the normalized origin point location, default [0.5;0.5]
+         *  - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
+         *  - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
+         *  - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
+         *  - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
+         *  - borderThickness: the thickness of the drawn border, default is 1.
+         *  - isVisible: true if the primitive must be visible, false for hidden. Default is true.
+         *  - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
+         *  - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
+         *  - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
+         */
+        Ellipse2D.Create = function (parent, options) {
+            BABYLON.Prim2DBase.CheckParent(parent);
+            var ellipse = new Ellipse2D();
+            if (!options) {
+                ellipse.setupEllipse2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, new BABYLON.Size(10, 10), 64, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"), null, 1, true, null, null, null, null, null, null);
+            }
+            else {
+                var fill;
+                if (options.fill === undefined) {
+                    fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
+                }
+                else {
+                    fill = options.fill;
+                }
+                var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
+                var size = options.size || (new BABYLON.Size(options.width || 10, options.height || 10));
+                ellipse.setupEllipse2D(parent.owner, parent, options.id || null, pos, options.origin || null, size, (options.subdivisions == null) ? 64 : options.subdivisions, fill, options.border || null, (options.borderThickness == null) ? 1 : options.borderThickness, (options.isVisible == null) ? true : options.isVisible, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
+            }
+            return ellipse;
+        };
+        Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            // Need to create WebGL resources for fill part?
+            if (this.fill) {
+                var vbSize = this.subdivisions + 1;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.fillVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize - 1;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < triCount; i++) {
+                    ib[i * 3 + 0] = 0;
+                    ib[i * 3 + 2] = i + 1;
+                    ib[i * 3 + 1] = i + 2;
+                }
+                ib[triCount * 3 - 2] = 1;
+                renderCache.fillIB = engine.createIndexBuffer(ib);
+                renderCache.fillIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
+                if (ei) {
+                    renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
+                renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            // Need to create WebGL resource for border part?
+            if (this.border) {
+                var vbSize = this.subdivisions * 2;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.borderVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize;
+                var rs = triCount / 2;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < rs; i++) {
+                    var r0 = i;
+                    var r1 = (i + 1) % rs;
+                    ib[i * 6 + 0] = rs + r1;
+                    ib[i * 6 + 1] = rs + r0;
+                    ib[i * 6 + 2] = r0;
+                    ib[i * 6 + 3] = r1;
+                    ib[i * 6 + 4] = rs + r1;
+                    ib[i * 6 + 5] = r0;
+                }
+                renderCache.borderIB = engine.createIndexBuffer(ib);
+                renderCache.borderIndicesCount = (triCount * 3);
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
+                if (ei) {
+                    renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
+                renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            return renderCache;
+        };
+        Ellipse2D.prototype.createInstanceDataParts = function () {
+            var res = new Array();
+            if (this.border) {
+                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
+            }
+            if (this.fill) {
+                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
+            }
+            return res;
+        };
+        Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
+                var d = part;
+                var size = this.size;
+                d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
+            }
+            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
+                var d = part;
+                var size = this.size;
+                d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
+            }
+            return true;
+        };
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.sizeProperty = pi; }, false, true)
+        ], Ellipse2D.prototype, "size", null);
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
+        ], Ellipse2D.prototype, "subdivisions", null);
+        Ellipse2D = __decorate([
+            BABYLON.className("Ellipse2D")
+        ], Ellipse2D);
+        return Ellipse2D;
+    })(BABYLON.Shape2D);
+    BABYLON.Ellipse2D = Ellipse2D;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1088 - 1127
src/Canvas2d/babylon.lines2d.js


+ 311 - 312
src/Canvas2d/babylon.modelRenderCache.js

@@ -1,312 +1,311 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var GroupInstanceInfo = (function () {
-        function GroupInstanceInfo(owner, mrc, partCount) {
-            this._partCount = partCount;
-            this.owner = owner;
-            this.modelRenderCache = mrc;
-            this.modelRenderCache.addRef();
-            this.partIndexFromId = new BABYLON.StringDictionary();
-            this._usedShaderCategories = new Array(partCount);
-            this._strides = new Array(partCount);
-            this._opaqueData = null;
-            this._alphaTestData = null;
-            this._transparentData = null;
-            this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
-        }
-        GroupInstanceInfo.prototype.dispose = function () {
-            if (this._isDisposed) {
-                return false;
-            }
-            if (this.modelRenderCache) {
-                this.modelRenderCache.dispose();
-            }
-            var engine = this.owner.owner.engine;
-            if (this.opaqueData) {
-                this.opaqueData.forEach(function (d) { return d.dispose(engine); });
-                this.opaqueData = null;
-            }
-            this.partIndexFromId = null;
-            this._isDisposed = true;
-            return true;
-        };
-        Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
-            get: function () {
-                return this._opaqueData != null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
-            get: function () {
-                return this._alphaTestData != null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
-            get: function () {
-                return this._transparentData != null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
-            get: function () {
-                if (!this._opaqueData) {
-                    this._opaqueData = new Array(this._partCount);
-                    for (var i = 0; i < this._partCount; i++) {
-                        this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
-                    }
-                }
-                return this._opaqueData;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
-            get: function () {
-                if (!this._alphaTestData) {
-                    this._alphaTestData = new Array(this._partCount);
-                    for (var i = 0; i < this._partCount; i++) {
-                        this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
-                    }
-                }
-                return this._alphaTestData;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
-            get: function () {
-                if (!this._transparentData) {
-                    this._transparentData = new Array(this._partCount);
-                    for (var i = 0; i < this._partCount; i++) {
-                        var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
-                        this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
-                    }
-                }
-                return this._transparentData;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        GroupInstanceInfo.prototype.sortTransparentData = function () {
-            if (!this.transparentOrderDirty) {
-                return;
-            }
-            for (var i = 0; i < this._transparentData.length; i++) {
-                var td = this._transparentData[i];
-                td._partData.sort();
-            }
-            this.transparentOrderDirty = false;
-        };
-        Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
-            get: function () {
-                return this._usedShaderCategories;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
-            get: function () {
-                return this._strides;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        return GroupInstanceInfo;
-    }());
-    BABYLON.GroupInstanceInfo = GroupInstanceInfo;
-    var TransparentSegment = (function () {
-        function TransparentSegment() {
-        }
-        return TransparentSegment;
-    }());
-    BABYLON.TransparentSegment = TransparentSegment;
-    var GroupInfoPartData = (function () {
-        function GroupInfoPartData(stride) {
-            this._partData = null;
-            this._partBuffer = null;
-            this._partBufferSize = 0;
-            this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
-            this._isDisposed = false;
-        }
-        GroupInfoPartData.prototype.dispose = function (engine) {
-            if (this._isDisposed) {
-                return false;
-            }
-            if (this._partBuffer) {
-                engine._releaseBuffer(this._partBuffer);
-                this._partBuffer = null;
-            }
-            this._partData = null;
-            this._isDisposed = true;
-        };
-        return GroupInfoPartData;
-    }());
-    BABYLON.GroupInfoPartData = GroupInfoPartData;
-    var TransparentGroupInfoPartData = (function (_super) {
-        __extends(TransparentGroupInfoPartData, _super);
-        function TransparentGroupInfoPartData(stride, zoff) {
-            _super.call(this, stride);
-            this._partData.compareValueOffset = zoff;
-            this._partData.sortingAscending = false;
-        }
-        return TransparentGroupInfoPartData;
-    }(GroupInfoPartData));
-    BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
-    var ModelRenderCache = (function () {
-        function ModelRenderCache(engine, modelKey) {
-            this._engine = engine;
-            this._modelKey = modelKey;
-            this._nextKey = 1;
-            this._refCounter = 1;
-            this._instancesData = new BABYLON.StringDictionary();
-            this._partData = null;
-        }
-        ModelRenderCache.prototype.dispose = function () {
-            if (--this._refCounter !== 0) {
-                return false;
-            }
-            // Remove the Model Render Cache from the global dictionary
-            var edata = this._engine.getExternalData("__BJSCANVAS2D__");
-            if (edata) {
-                edata.DisposeModelRenderCache(this);
-            }
-            return true;
-        };
-        Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
-            get: function () {
-                return this._refCounter <= 0;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ModelRenderCache.prototype.addRef = function () {
-            return ++this._refCounter;
-        };
-        Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
-            get: function () {
-                return this._modelKey;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Render the model instances
-         * @param instanceInfo
-         * @param context
-         * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
-         */
-        ModelRenderCache.prototype.render = function (instanceInfo, context) {
-            return true;
-        };
-        ModelRenderCache.prototype.addInstanceDataParts = function (data) {
-            var key = this._nextKey.toString();
-            if (!this._instancesData.add(key, data)) {
-                throw Error("Key: " + key + " is already allocated");
-            }
-            ++this._nextKey;
-            return key;
-        };
-        ModelRenderCache.prototype.removeInstanceData = function (key) {
-            this._instancesData.remove(key);
-        };
-        ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
-            for (var i = 0; i < this._partData.length; i++) {
-                if (this._partData[i]._partId === partId) {
-                    return i;
-                }
-            }
-            return null;
-        };
-        ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
-            var i = this.getPartIndexFromId(partId);
-            if (i === null) {
-                return null;
-            }
-            var ci = this._partsClassInfo[i];
-            var categories = this._partData[i]._partUsedCategories;
-            var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
-            return res;
-        };
-        ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
-            var pd = this._partData[partIndex];
-            var offset = (pd._partDataStride / 4) * elementCount;
-            var pci = this._partsClassInfo[partIndex];
-            var self = this;
-            pci.fullContent.forEach(function (k, v) {
-                if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
-                    switch (v.dataType) {
-                        case 4 /* float */:
-                            {
-                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
-                                effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
-                                break;
-                            }
-                        case 0 /* Vector2 */:
-                            {
-                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
-                                ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
-                                ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
-                                effect.setVector2(v.attributeName, ModelRenderCache.v2);
-                                break;
-                            }
-                        case 5 /* Color3 */:
-                        case 1 /* Vector3 */:
-                            {
-                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
-                                ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
-                                ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
-                                ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
-                                effect.setVector3(v.attributeName, ModelRenderCache.v3);
-                                break;
-                            }
-                        case 6 /* Color4 */:
-                        case 2 /* Vector4 */:
-                            {
-                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
-                                ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
-                                ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
-                                ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
-                                ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
-                                effect.setVector4(v.attributeName, ModelRenderCache.v4);
-                                break;
-                            }
-                        default:
-                    }
-                }
-            });
-        };
-        //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
-        //    let i = this.getPartIndexFromId(partId);
-        //    if (i === null) {
-        //        return null;
-        //    }
-        //    let pci = this._partsClassInfo[i];
-        //    pci.fullContent.forEach((k, v) => {
-        //        if (uniforms.indexOf(v.attributeName) !== -1) {
-        //            v.uniformLocation = effect.getUniform(v.attributeName);
-        //        }
-        //    });
-        //}
-        ModelRenderCache.v2 = BABYLON.Vector2.Zero();
-        ModelRenderCache.v3 = BABYLON.Vector3.Zero();
-        ModelRenderCache.v4 = BABYLON.Vector4.Zero();
-        return ModelRenderCache;
-    }());
-    BABYLON.ModelRenderCache = ModelRenderCache;
-    var ModelRenderCachePartData = (function () {
-        function ModelRenderCachePartData() {
-        }
-        return ModelRenderCachePartData;
-    }());
-    BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.modelRenderCache.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var GroupInstanceInfo = (function () {
+        function GroupInstanceInfo(owner, mrc, partCount) {
+            this._partCount = partCount;
+            this.owner = owner;
+            this.modelRenderCache = mrc;
+            this.modelRenderCache.addRef();
+            this.partIndexFromId = new BABYLON.StringDictionary();
+            this._usedShaderCategories = new Array(partCount);
+            this._strides = new Array(partCount);
+            this._opaqueData = null;
+            this._alphaTestData = null;
+            this._transparentData = null;
+            this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
+        }
+        GroupInstanceInfo.prototype.dispose = function () {
+            if (this._isDisposed) {
+                return false;
+            }
+            if (this.modelRenderCache) {
+                this.modelRenderCache.dispose();
+            }
+            var engine = this.owner.owner.engine;
+            if (this.opaqueData) {
+                this.opaqueData.forEach(function (d) { return d.dispose(engine); });
+                this.opaqueData = null;
+            }
+            this.partIndexFromId = null;
+            this._isDisposed = true;
+            return true;
+        };
+        Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
+            get: function () {
+                return this._opaqueData != null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
+            get: function () {
+                return this._alphaTestData != null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
+            get: function () {
+                return this._transparentData != null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
+            get: function () {
+                if (!this._opaqueData) {
+                    this._opaqueData = new Array(this._partCount);
+                    for (var i = 0; i < this._partCount; i++) {
+                        this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
+                    }
+                }
+                return this._opaqueData;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
+            get: function () {
+                if (!this._alphaTestData) {
+                    this._alphaTestData = new Array(this._partCount);
+                    for (var i = 0; i < this._partCount; i++) {
+                        this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
+                    }
+                }
+                return this._alphaTestData;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
+            get: function () {
+                if (!this._transparentData) {
+                    this._transparentData = new Array(this._partCount);
+                    for (var i = 0; i < this._partCount; i++) {
+                        var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
+                        this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
+                    }
+                }
+                return this._transparentData;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        GroupInstanceInfo.prototype.sortTransparentData = function () {
+            if (!this.transparentOrderDirty) {
+                return;
+            }
+            for (var i = 0; i < this._transparentData.length; i++) {
+                var td = this._transparentData[i];
+                td._partData.sort();
+            }
+            this.transparentOrderDirty = false;
+        };
+        Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
+            get: function () {
+                return this._usedShaderCategories;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
+            get: function () {
+                return this._strides;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        return GroupInstanceInfo;
+    })();
+    BABYLON.GroupInstanceInfo = GroupInstanceInfo;
+    var TransparentSegment = (function () {
+        function TransparentSegment() {
+        }
+        return TransparentSegment;
+    })();
+    BABYLON.TransparentSegment = TransparentSegment;
+    var GroupInfoPartData = (function () {
+        function GroupInfoPartData(stride) {
+            this._partData = null;
+            this._partBuffer = null;
+            this._partBufferSize = 0;
+            this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
+            this._isDisposed = false;
+        }
+        GroupInfoPartData.prototype.dispose = function (engine) {
+            if (this._isDisposed) {
+                return false;
+            }
+            if (this._partBuffer) {
+                engine._releaseBuffer(this._partBuffer);
+                this._partBuffer = null;
+            }
+            this._partData = null;
+            this._isDisposed = true;
+        };
+        return GroupInfoPartData;
+    })();
+    BABYLON.GroupInfoPartData = GroupInfoPartData;
+    var TransparentGroupInfoPartData = (function (_super) {
+        __extends(TransparentGroupInfoPartData, _super);
+        function TransparentGroupInfoPartData(stride, zoff) {
+            _super.call(this, stride);
+            this._partData.compareValueOffset = zoff;
+            this._partData.sortingAscending = false;
+        }
+        return TransparentGroupInfoPartData;
+    })(GroupInfoPartData);
+    BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
+    var ModelRenderCache = (function () {
+        function ModelRenderCache(engine, modelKey) {
+            this._engine = engine;
+            this._modelKey = modelKey;
+            this._nextKey = 1;
+            this._refCounter = 1;
+            this._instancesData = new BABYLON.StringDictionary();
+            this._partData = null;
+        }
+        ModelRenderCache.prototype.dispose = function () {
+            if (--this._refCounter !== 0) {
+                return false;
+            }
+            // Remove the Model Render Cache from the global dictionary
+            var edata = this._engine.getExternalData("__BJSCANVAS2D__");
+            if (edata) {
+                edata.DisposeModelRenderCache(this);
+            }
+            return true;
+        };
+        Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
+            get: function () {
+                return this._refCounter <= 0;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ModelRenderCache.prototype.addRef = function () {
+            return ++this._refCounter;
+        };
+        Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
+            get: function () {
+                return this._modelKey;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Render the model instances
+         * @param instanceInfo
+         * @param context
+         * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
+         */
+        ModelRenderCache.prototype.render = function (instanceInfo, context) {
+            return true;
+        };
+        ModelRenderCache.prototype.addInstanceDataParts = function (data) {
+            var key = this._nextKey.toString();
+            if (!this._instancesData.add(key, data)) {
+                throw Error("Key: " + key + " is already allocated");
+            }
+            ++this._nextKey;
+            return key;
+        };
+        ModelRenderCache.prototype.removeInstanceData = function (key) {
+            this._instancesData.remove(key);
+        };
+        ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
+            for (var i = 0; i < this._partData.length; i++) {
+                if (this._partData[i]._partId === partId) {
+                    return i;
+                }
+            }
+            return null;
+        };
+        ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
+            var i = this.getPartIndexFromId(partId);
+            if (i === null) {
+                return null;
+            }
+            var ci = this._partsClassInfo[i];
+            var categories = this._partData[i]._partUsedCategories;
+            var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
+            return res;
+        };
+        ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
+            var pd = this._partData[partIndex];
+            var offset = (pd._partDataStride / 4) * elementCount;
+            var pci = this._partsClassInfo[partIndex];
+            var self = this;
+            pci.fullContent.forEach(function (k, v) {
+                if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
+                    switch (v.dataType) {
+                        case 4 /* float */:
+                            {
+                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
+                                effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
+                                break;
+                            }
+                        case 0 /* Vector2 */:
+                            {
+                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
+                                ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
+                                ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
+                                effect.setVector2(v.attributeName, ModelRenderCache.v2);
+                                break;
+                            }
+                        case 5 /* Color3 */:
+                        case 1 /* Vector3 */:
+                            {
+                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
+                                ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
+                                ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
+                                ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
+                                effect.setVector3(v.attributeName, ModelRenderCache.v3);
+                                break;
+                            }
+                        case 6 /* Color4 */:
+                        case 2 /* Vector4 */:
+                            {
+                                var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
+                                ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
+                                ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
+                                ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
+                                ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
+                                effect.setVector4(v.attributeName, ModelRenderCache.v4);
+                                break;
+                            }
+                        default:
+                    }
+                }
+            });
+        };
+        //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
+        //    let i = this.getPartIndexFromId(partId);
+        //    if (i === null) {
+        //        return null;
+        //    }
+        //    let pci = this._partsClassInfo[i];
+        //    pci.fullContent.forEach((k, v) => {
+        //        if (uniforms.indexOf(v.attributeName) !== -1) {
+        //            v.uniformLocation = effect.getUniform(v.attributeName);
+        //        }
+        //    });
+        //}
+        ModelRenderCache.v2 = BABYLON.Vector2.Zero();
+        ModelRenderCache.v3 = BABYLON.Vector3.Zero();
+        ModelRenderCache.v4 = BABYLON.Vector4.Zero();
+        return ModelRenderCache;
+    })();
+    BABYLON.ModelRenderCache = ModelRenderCache;
+    var ModelRenderCachePartData = (function () {
+        function ModelRenderCachePartData() {
+        }
+        return ModelRenderCachePartData;
+    })();
+    BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1016 - 2181
src/Canvas2d/babylon.prim2dBase.js


+ 415 - 432
src/Canvas2d/babylon.rectangle2d.js

@@ -1,432 +1,415 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Rectangle2DRenderCache = (function (_super) {
-        __extends(Rectangle2DRenderCache, _super);
-        function Rectangle2DRenderCache(engine, modelKey) {
-            _super.call(this, engine, modelKey);
-            this.effectsReady = false;
-            this.fillVB = null;
-            this.fillIB = null;
-            this.fillIndicesCount = 0;
-            this.instancingFillAttributes = null;
-            this.effectFill = null;
-            this.effectFillInstanced = null;
-            this.borderVB = null;
-            this.borderIB = null;
-            this.borderIndicesCount = 0;
-            this.instancingBorderAttributes = null;
-            this.effectBorder = null;
-            this.effectBorderInstanced = null;
-        }
-        Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
-                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            var engine = instanceInfo.owner.owner.engine;
-            var depthFunction = 0;
-            if (this.effectFill && this.effectBorder) {
-                depthFunction = engine.getDepthFunction();
-                engine.setDepthFunctionToLessOrEqual();
-            }
-            var curAlphaMode = engine.getAlphaMode();
-            if (this.effectFill) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-                }
-                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingFillAttributes) {
-                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
-                    }
-                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
-                    engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.fillIndicesCount);
-                    }
-                }
-            }
-            if (this.effectBorder) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-                }
-                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingBorderAttributes) {
-                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
-                    }
-                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
-                    engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.borderIndicesCount);
-                    }
-                }
-            }
-            engine.setAlphaMode(curAlphaMode);
-            if (this.effectFill && this.effectBorder) {
-                engine.setDepthFunction(depthFunction);
-            }
-            return true;
-        };
-        Rectangle2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.fillVB) {
-                this._engine._releaseBuffer(this.fillVB);
-                this.fillVB = null;
-            }
-            if (this.fillIB) {
-                this._engine._releaseBuffer(this.fillIB);
-                this.fillIB = null;
-            }
-            if (this.effectFill) {
-                this._engine._releaseEffect(this.effectFill);
-                this.effectFill = null;
-            }
-            if (this.effectFillInstanced) {
-                this._engine._releaseEffect(this.effectFillInstanced);
-                this.effectFillInstanced = null;
-            }
-            if (this.borderVB) {
-                this._engine._releaseBuffer(this.borderVB);
-                this.borderVB = null;
-            }
-            if (this.borderIB) {
-                this._engine._releaseBuffer(this.borderIB);
-                this.borderIB = null;
-            }
-            if (this.effectBorder) {
-                this._engine._releaseEffect(this.effectBorder);
-                this.effectBorder = null;
-            }
-            if (this.effectBorderInstanced) {
-                this._engine._releaseEffect(this.effectBorderInstanced);
-                this.effectBorderInstanced = null;
-            }
-            return true;
-        };
-        return Rectangle2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
-    var Rectangle2DInstanceData = (function (_super) {
-        __extends(Rectangle2DInstanceData, _super);
-        function Rectangle2DInstanceData(partId) {
-            _super.call(this, partId, 1);
-        }
-        Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Rectangle2DInstanceData.prototype, "properties", null);
-        return Rectangle2DInstanceData;
-    }(BABYLON.Shape2DInstanceData));
-    BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
-    var Rectangle2D = (function (_super) {
-        __extends(Rectangle2D, _super);
-        //protected setupRectangle2D(owner: Canvas2D, parent: Prim2DBase, id: string, position: Vector2, origin: Vector2, size: Size, roundRadius, fill: IBrush2D, border: IBrush2D, borderThickness: number, isVisible: boolean, marginTop: number | string, marginLeft: number | string, marginRight: number | string, marginBottom: number | string, vAlignment: number, hAlignment: number) {
-        //    this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
-        //    this.size = size;
-        //    this.notRounded = !roundRadius;
-        //    this.roundRadius = roundRadius;
-        //}
-        /**
-         * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
-         * @param parent the parent primitive, must be a valid primitive (or the Canvas)
-         * options:
-         *  - id a text identifier, for information purpose
-         *  - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
-         *  - origin: define the normalized origin point location, default [0.5;0.5]
-         *  - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
-         *  - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp rectangle).
-         *  - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
-         *  - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
-         *  - borderThickness: the thickness of the drawn border, default is 1.
-         *  - isVisible: true if the primitive must be visible, false for hidden. Default is true.
-         *  - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
-         *  - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
-         *  - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
-         */
-        function Rectangle2D(settings) {
-            // Avoid checking every time if the object exists
-            if (settings == null) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            var size = settings.size || (new BABYLON.Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
-            var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
-            var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
-            this.size = size;
-            this.roundRadius = roundRadius;
-            this.borderThickness = borderThickness;
-        }
-        Object.defineProperty(Rectangle2D.prototype, "size", {
-            //        @instanceLevelProperty(Shape2D.SHAPE2D_PROPCOUNT + 1, pi => Rectangle2D.sizeProperty = pi, false, true)
-            get: function () {
-                return this._size;
-            },
-            set: function (value) {
-                this._size = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Rectangle2D.prototype, "actualSize", {
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this._size;
-            },
-            set: function (value) {
-                this._actualSize = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Rectangle2D.prototype, "notRounded", {
-            get: function () {
-                return this._notRounded;
-            },
-            set: function (value) {
-                this._notRounded = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
-            get: function () {
-                return this._roundRadius;
-            },
-            set: function (value) {
-                this._roundRadius = value;
-                this.notRounded = value === 0;
-                this._positioningDirty();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
-            // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
-            if (this.notRounded) {
-                return true;
-            }
-            // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
-            // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
-            // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
-            // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
-            var size = this.size;
-            Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
-            Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
-            var rr = this.roundRadius;
-            var rrs = rr * rr;
-            // Check if the point is in the bottom/left quarter area
-            Rectangle2D._i1.x = rr;
-            Rectangle2D._i1.y = rr;
-            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the top/left quarter area
-            Rectangle2D._i1.x = rr;
-            Rectangle2D._i1.y = size.height - rr;
-            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the top/right quarter area
-            Rectangle2D._i1.x = size.width - rr;
-            Rectangle2D._i1.y = size.height - rr;
-            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the bottom/right quarter area
-            Rectangle2D._i1.x = size.width - rr;
-            Rectangle2D._i1.y = rr;
-            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // At any other locations the point is guarantied to be inside
-            return true;
-        };
-        Rectangle2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
-        };
-        Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            // Need to create WebGL resources for fill part?
-            if (this.fill) {
-                var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.fillVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize - 1;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < triCount; i++) {
-                    ib[i * 3 + 0] = 0;
-                    ib[i * 3 + 2] = i + 1;
-                    ib[i * 3 + 1] = i + 2;
-                }
-                ib[triCount * 3 - 2] = 1;
-                renderCache.fillIB = engine.createIndexBuffer(ib);
-                renderCache.fillIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
-                if (ei) {
-                    renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
-                renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            // Need to create WebGL resource for border part?
-            if (this.border) {
-                var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.borderVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize;
-                var rs = triCount / 2;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < rs; i++) {
-                    var r0 = i;
-                    var r1 = (i + 1) % rs;
-                    ib[i * 6 + 0] = rs + r1;
-                    ib[i * 6 + 1] = rs + r0;
-                    ib[i * 6 + 2] = r0;
-                    ib[i * 6 + 3] = r1;
-                    ib[i * 6 + 4] = rs + r1;
-                    ib[i * 6 + 5] = r0;
-                }
-                renderCache.borderIB = engine.createIndexBuffer(ib);
-                renderCache.borderIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
-                if (ei) {
-                    renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
-                renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            return renderCache;
-        };
-        // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
-        Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
-            // Fall back to default implementation if there's no round Radius
-            if (this._notRounded) {
-                _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
-            }
-            else {
-                var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
-                initialContentPosition.x = initialContentPosition.y = rr;
-                initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
-                initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
-            }
-        };
-        Rectangle2D.prototype.createInstanceDataParts = function () {
-            var res = new Array();
-            if (this.border) {
-                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
-            }
-            if (this.fill) {
-                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
-            }
-            return res;
-        };
-        Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
-            }
-            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
-            }
-            return true;
-        };
-        Rectangle2D._i0 = BABYLON.Vector2.Zero();
-        Rectangle2D._i1 = BABYLON.Vector2.Zero();
-        Rectangle2D._i2 = BABYLON.Vector2.Zero();
-        Rectangle2D.roundSubdivisions = 16;
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
-        ], Rectangle2D.prototype, "actualSize", null);
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
-        ], Rectangle2D.prototype, "notRounded", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
-        ], Rectangle2D.prototype, "roundRadius", null);
-        Rectangle2D = __decorate([
-            BABYLON.className("Rectangle2D")
-        ], Rectangle2D);
-        return Rectangle2D;
-    }(BABYLON.Shape2D));
-    BABYLON.Rectangle2D = Rectangle2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.rectangle2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Rectangle2DRenderCache = (function (_super) {
+        __extends(Rectangle2DRenderCache, _super);
+        function Rectangle2DRenderCache(engine, modelKey) {
+            _super.call(this, engine, modelKey);
+            this.effectsReady = false;
+            this.fillVB = null;
+            this.fillIB = null;
+            this.fillIndicesCount = 0;
+            this.instancingFillAttributes = null;
+            this.effectFill = null;
+            this.effectFillInstanced = null;
+            this.borderVB = null;
+            this.borderIB = null;
+            this.borderIndicesCount = 0;
+            this.instancingBorderAttributes = null;
+            this.effectBorder = null;
+            this.effectBorderInstanced = null;
+        }
+        Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
+                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            var engine = instanceInfo.owner.owner.engine;
+            var depthFunction = 0;
+            if (this.effectFill && this.effectBorder) {
+                depthFunction = engine.getDepthFunction();
+                engine.setDepthFunctionToLessOrEqual();
+            }
+            var curAlphaMode = engine.getAlphaMode();
+            if (this.effectFill) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+                }
+                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingFillAttributes) {
+                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
+                    }
+                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
+                    engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.fillIndicesCount);
+                    }
+                }
+            }
+            if (this.effectBorder) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+                }
+                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingBorderAttributes) {
+                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
+                    }
+                    engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
+                    engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.borderIndicesCount);
+                    }
+                }
+            }
+            engine.setAlphaMode(curAlphaMode);
+            if (this.effectFill && this.effectBorder) {
+                engine.setDepthFunction(depthFunction);
+            }
+            return true;
+        };
+        Rectangle2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.fillVB) {
+                this._engine._releaseBuffer(this.fillVB);
+                this.fillVB = null;
+            }
+            if (this.fillIB) {
+                this._engine._releaseBuffer(this.fillIB);
+                this.fillIB = null;
+            }
+            if (this.effectFill) {
+                this._engine._releaseEffect(this.effectFill);
+                this.effectFill = null;
+            }
+            if (this.effectFillInstanced) {
+                this._engine._releaseEffect(this.effectFillInstanced);
+                this.effectFillInstanced = null;
+            }
+            if (this.borderVB) {
+                this._engine._releaseBuffer(this.borderVB);
+                this.borderVB = null;
+            }
+            if (this.borderIB) {
+                this._engine._releaseBuffer(this.borderIB);
+                this.borderIB = null;
+            }
+            if (this.effectBorder) {
+                this._engine._releaseEffect(this.effectBorder);
+                this.effectBorder = null;
+            }
+            if (this.effectBorderInstanced) {
+                this._engine._releaseEffect(this.effectBorderInstanced);
+                this.effectBorderInstanced = null;
+            }
+            return true;
+        };
+        return Rectangle2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
+    var Rectangle2DInstanceData = (function (_super) {
+        __extends(Rectangle2DInstanceData, _super);
+        function Rectangle2DInstanceData(partId) {
+            _super.call(this, partId, 1);
+        }
+        Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Rectangle2DInstanceData.prototype, "properties", null);
+        return Rectangle2DInstanceData;
+    })(BABYLON.Shape2DInstanceData);
+    BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
+    var Rectangle2D = (function (_super) {
+        __extends(Rectangle2D, _super);
+        function Rectangle2D() {
+            _super.apply(this, arguments);
+        }
+        Object.defineProperty(Rectangle2D.prototype, "actualSize", {
+            get: function () {
+                return this.size;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Rectangle2D.prototype, "size", {
+            get: function () {
+                return this._size;
+            },
+            set: function (value) {
+                this._size = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Rectangle2D.prototype, "notRounded", {
+            get: function () {
+                return this._notRounded;
+            },
+            set: function (value) {
+                this._notRounded = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
+            get: function () {
+                return this._roundRadius;
+            },
+            set: function (value) {
+                this._roundRadius = value;
+                this.notRounded = value === 0;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
+            // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
+            if (this.notRounded) {
+                return true;
+            }
+            // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
+            // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
+            // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
+            // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
+            var o = this.origin;
+            var size = this.size;
+            Rectangle2D._i0.x = intersectInfo._localPickPosition.x + (size.width * o.x);
+            Rectangle2D._i0.y = intersectInfo._localPickPosition.y + (size.height * o.y);
+            var rr = this.roundRadius;
+            var rrs = rr * rr;
+            // Check if the point is in the bottom/left quarter area
+            Rectangle2D._i1.x = rr;
+            Rectangle2D._i1.y = rr;
+            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the top/left quarter area
+            Rectangle2D._i1.x = rr;
+            Rectangle2D._i1.y = size.height - rr;
+            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the top/right quarter area
+            Rectangle2D._i1.x = size.width - rr;
+            Rectangle2D._i1.y = size.height - rr;
+            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the bottom/right quarter area
+            Rectangle2D._i1.x = size.width - rr;
+            Rectangle2D._i1.y = rr;
+            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // At any other locations the point is guarantied to be inside
+            return true;
+        };
+        Rectangle2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
+        };
+        Rectangle2D.prototype.setupRectangle2D = function (owner, parent, id, position, origin, size, roundRadius, fill, border, borderThickness, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
+            this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
+            this.size = size;
+            this.notRounded = !roundRadius;
+            this.roundRadius = roundRadius;
+        };
+        /**
+         * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
+         * @param parent the parent primitive, must be a valid primitive (or the Canvas)
+         * options:
+         *  - id a text identifier, for information purpose
+         *  - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
+         *  - origin: define the normalized origin point location, default [0.5;0.5]
+         *  - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
+         *  - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp rectangle).
+         *  - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
+         *  - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
+         *  - borderThickness: the thickness of the drawn border, default is 1.
+         *  - isVisible: true if the primitive must be visible, false for hidden. Default is true.
+         *  - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
+         *  - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
+         *  - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
+         */
+        Rectangle2D.Create = function (parent, options) {
+            BABYLON.Prim2DBase.CheckParent(parent);
+            var rect = new Rectangle2D();
+            if (!options) {
+                rect.setupRectangle2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, new BABYLON.Size(10, 10), 0, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"), null, 1, true, null, null, null, null, null, null);
+            }
+            else {
+                var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
+                var size = options.size || (new BABYLON.Size(options.width || 10, options.height || 10));
+                var fill = options.fill === undefined ? BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF") : options.fill;
+                rect.setupRectangle2D(parent.owner, parent, options.id || null, pos, options.origin || null, size, (options.roundRadius == null) ? 0 : options.roundRadius, fill, options.border || null, (options.borderThickness == null) ? 1 : options.borderThickness, options.isVisible || true, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
+            }
+            return rect;
+        };
+        Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            // Need to create WebGL resources for fill part?
+            if (this.fill) {
+                var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.fillVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize - 1;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < triCount; i++) {
+                    ib[i * 3 + 0] = 0;
+                    ib[i * 3 + 2] = i + 1;
+                    ib[i * 3 + 1] = i + 2;
+                }
+                ib[triCount * 3 - 2] = 1;
+                renderCache.fillIB = engine.createIndexBuffer(ib);
+                renderCache.fillIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
+                if (ei) {
+                    renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
+                renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            // Need to create WebGL resource for border part?
+            if (this.border) {
+                var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.borderVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize;
+                var rs = triCount / 2;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < rs; i++) {
+                    var r0 = i;
+                    var r1 = (i + 1) % rs;
+                    ib[i * 6 + 0] = rs + r1;
+                    ib[i * 6 + 1] = rs + r0;
+                    ib[i * 6 + 2] = r0;
+                    ib[i * 6 + 3] = r1;
+                    ib[i * 6 + 4] = rs + r1;
+                    ib[i * 6 + 5] = r0;
+                }
+                renderCache.borderIB = engine.createIndexBuffer(ib);
+                renderCache.borderIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
+                if (ei) {
+                    renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
+                renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            return renderCache;
+        };
+        Rectangle2D.prototype.createInstanceDataParts = function () {
+            var res = new Array();
+            if (this.border) {
+                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
+            }
+            if (this.fill) {
+                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
+            }
+            return res;
+        };
+        Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
+                var d = part;
+                var size = this.size;
+                d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
+            }
+            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
+                var d = part;
+                var size = this.size;
+                d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
+            }
+            return true;
+        };
+        Rectangle2D._i0 = BABYLON.Vector2.Zero();
+        Rectangle2D._i1 = BABYLON.Vector2.Zero();
+        Rectangle2D._i2 = BABYLON.Vector2.Zero();
+        Rectangle2D.roundSubdivisions = 16;
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.sizeProperty = pi; }, false, true)
+        ], Rectangle2D.prototype, "size", null);
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
+        ], Rectangle2D.prototype, "notRounded", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
+        ], Rectangle2D.prototype, "roundRadius", null);
+        Rectangle2D = __decorate([
+            BABYLON.className("Rectangle2D")
+        ], Rectangle2D);
+        return Rectangle2D;
+    })(BABYLON.Shape2D);
+    BABYLON.Rectangle2D = Rectangle2D;
+})(BABYLON || (BABYLON = {}));

+ 248 - 267
src/Canvas2d/babylon.shape2d.js

@@ -1,267 +1,248 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Shape2D = (function (_super) {
-        __extends(Shape2D, _super);
-        function Shape2D(settings) {
-            _super.call(this, settings);
-            if (!settings) {
-                settings = {};
-            }
-            var borderBrush = null;
-            if (settings.border) {
-                if (typeof (settings.border) === "string") {
-                    borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
-                }
-                else {
-                    borderBrush = settings.border;
-                }
-            }
-            var fillBrush = null;
-            if (settings.fill) {
-                if (typeof (settings.fill) === "string") {
-                    fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
-                }
-                else {
-                    fillBrush = settings.fill;
-                }
-            }
-            this.border = borderBrush;
-            this.fill = fillBrush;
-            this.borderThickness = settings.borderThickness;
-        }
-        Object.defineProperty(Shape2D.prototype, "border", {
-            get: function () {
-                return this._border;
-            },
-            set: function (value) {
-                this._border = value;
-                this._updateTransparencyStatus();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2D.prototype, "fill", {
-            get: function () {
-                return this._fill;
-            },
-            set: function (value) {
-                this._fill = value;
-                this._updateTransparencyStatus();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2D.prototype, "borderThickness", {
-            get: function () {
-                return this._borderThickness;
-            },
-            set: function (value) {
-                this._borderThickness = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
-            var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
-            // Fill Part
-            if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
-                var fill = this.fill;
-                if (fill instanceof BABYLON.SolidColorBrush2D) {
-                    cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
-                }
-                if (fill instanceof BABYLON.GradientColorBrush2D) {
-                    cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
-                }
-            }
-            // Border Part
-            if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
-                cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
-                var border = this.border;
-                if (border instanceof BABYLON.SolidColorBrush2D) {
-                    cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
-                }
-                if (border instanceof BABYLON.GradientColorBrush2D) {
-                    cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
-                }
-            }
-            return cat;
-        };
-        Shape2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            // Fill Part
-            if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
-                var d = part;
-                if (this.fill) {
-                    var fill = this.fill;
-                    if (fill instanceof BABYLON.SolidColorBrush2D) {
-                        d.fillSolidColor = fill.color;
-                    }
-                    else if (fill instanceof BABYLON.GradientColorBrush2D) {
-                        d.fillGradientColor1 = fill.color1;
-                        d.fillGradientColor2 = fill.color2;
-                        var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
-                        var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
-                        d.fillGradientTY = ty;
-                    }
-                }
-            }
-            else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
-                var d = part;
-                if (this.border) {
-                    d.borderThickness = this.borderThickness;
-                    var border = this.border;
-                    if (border instanceof BABYLON.SolidColorBrush2D) {
-                        d.borderSolidColor = border.color;
-                    }
-                    else if (border instanceof BABYLON.GradientColorBrush2D) {
-                        d.borderGradientColor1 = border.color1;
-                        d.borderGradientColor2 = border.color2;
-                        var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
-                        var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
-                        d.borderGradientTY = ty;
-                    }
-                }
-            }
-            return true;
-        };
-        Shape2D.prototype._updateTransparencyStatus = function () {
-            this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
-        };
-        Shape2D.SHAPE2D_BORDERPARTID = 1;
-        Shape2D.SHAPE2D_FILLPARTID = 2;
-        Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
-        Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
-        Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
-        Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
-        Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
-        Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
-        ], Shape2D.prototype, "border", null);
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
-        ], Shape2D.prototype, "fill", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
-        ], Shape2D.prototype, "borderThickness", null);
-        Shape2D = __decorate([
-            BABYLON.className("Shape2D")
-        ], Shape2D);
-        return Shape2D;
-    }(BABYLON.RenderablePrim2D));
-    BABYLON.Shape2D = Shape2D;
-    var Shape2DInstanceData = (function (_super) {
-        __extends(Shape2DInstanceData, _super);
-        function Shape2DInstanceData() {
-            _super.apply(this, arguments);
-        }
-        Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
-            // FILL ATTRIBUTES
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
-            // BORDER ATTRIBUTES
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
-        ], Shape2DInstanceData.prototype, "fillSolidColor", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
-        ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
-        ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
-        ], Shape2DInstanceData.prototype, "fillGradientTY", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
-        ], Shape2DInstanceData.prototype, "borderThickness", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
-        ], Shape2DInstanceData.prototype, "borderSolidColor", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
-        ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
-        ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
-        __decorate([
-            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
-        ], Shape2DInstanceData.prototype, "borderGradientTY", null);
-        return Shape2DInstanceData;
-    }(BABYLON.InstanceDataBase));
-    BABYLON.Shape2DInstanceData = Shape2DInstanceData;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.shape2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Shape2D = (function (_super) {
+        __extends(Shape2D, _super);
+        function Shape2D() {
+            _super.apply(this, arguments);
+        }
+        Object.defineProperty(Shape2D.prototype, "border", {
+            get: function () {
+                return this._border;
+            },
+            set: function (value) {
+                this._border = value;
+                this._updateTransparencyStatus();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2D.prototype, "fill", {
+            get: function () {
+                return this._fill;
+            },
+            set: function (value) {
+                this._fill = value;
+                this._updateTransparencyStatus();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2D.prototype, "borderThickness", {
+            get: function () {
+                return this._borderThickness;
+            },
+            set: function (value) {
+                this._borderThickness = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Shape2D.prototype.setupShape2D = function (owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
+            this.setupRenderablePrim2D(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlignment || BABYLON.Prim2DBase.HAlignLeft, vAlignment || BABYLON.Prim2DBase.VAlignTop);
+            this.border = border;
+            this.fill = fill;
+            this.borderThickness = borderThickness;
+        };
+        Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
+            var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
+            // Fill Part
+            if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
+                var fill = this.fill;
+                if (fill instanceof BABYLON.SolidColorBrush2D) {
+                    cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
+                }
+                if (fill instanceof BABYLON.GradientColorBrush2D) {
+                    cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
+                }
+            }
+            // Border Part
+            if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
+                cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
+                var border = this.border;
+                if (border instanceof BABYLON.SolidColorBrush2D) {
+                    cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
+                }
+                if (border instanceof BABYLON.GradientColorBrush2D) {
+                    cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
+                }
+            }
+            return cat;
+        };
+        Shape2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            // Fill Part
+            if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
+                var d = part;
+                if (this.fill) {
+                    var fill = this.fill;
+                    if (fill instanceof BABYLON.SolidColorBrush2D) {
+                        d.fillSolidColor = fill.color;
+                    }
+                    else if (fill instanceof BABYLON.GradientColorBrush2D) {
+                        d.fillGradientColor1 = fill.color1;
+                        d.fillGradientColor2 = fill.color2;
+                        var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
+                        var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
+                        d.fillGradientTY = ty;
+                    }
+                }
+            }
+            else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
+                var d = part;
+                if (this.border) {
+                    d.borderThickness = this.borderThickness;
+                    var border = this.border;
+                    if (border instanceof BABYLON.SolidColorBrush2D) {
+                        d.borderSolidColor = border.color;
+                    }
+                    else if (border instanceof BABYLON.GradientColorBrush2D) {
+                        d.borderGradientColor1 = border.color1;
+                        d.borderGradientColor2 = border.color2;
+                        var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
+                        var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
+                        d.borderGradientTY = ty;
+                    }
+                }
+            }
+            return true;
+        };
+        Shape2D.prototype._updateTransparencyStatus = function () {
+            this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
+        };
+        Shape2D.SHAPE2D_BORDERPARTID = 1;
+        Shape2D.SHAPE2D_FILLPARTID = 2;
+        Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
+        Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
+        Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
+        Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
+        Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
+        Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
+        ], Shape2D.prototype, "border", null);
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
+        ], Shape2D.prototype, "fill", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
+        ], Shape2D.prototype, "borderThickness", null);
+        Shape2D = __decorate([
+            BABYLON.className("Shape2D")
+        ], Shape2D);
+        return Shape2D;
+    })(BABYLON.RenderablePrim2D);
+    BABYLON.Shape2D = Shape2D;
+    var Shape2DInstanceData = (function (_super) {
+        __extends(Shape2DInstanceData, _super);
+        function Shape2DInstanceData() {
+            _super.apply(this, arguments);
+        }
+        Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
+            // FILL ATTRIBUTES
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
+            // BORDER ATTRIBUTES
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
+        ], Shape2DInstanceData.prototype, "fillSolidColor", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
+        ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
+        ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
+        ], Shape2DInstanceData.prototype, "fillGradientTY", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
+        ], Shape2DInstanceData.prototype, "borderThickness", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
+        ], Shape2DInstanceData.prototype, "borderSolidColor", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
+        ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
+        ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
+        __decorate([
+            BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
+        ], Shape2DInstanceData.prototype, "borderGradientTY", null);
+        return Shape2DInstanceData;
+    })(BABYLON.InstanceDataBase);
+    BABYLON.Shape2DInstanceData = Shape2DInstanceData;
+})(BABYLON || (BABYLON = {}));

+ 445 - 523
src/Canvas2d/babylon.smartPropertyPrim.js

@@ -1,523 +1,445 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Prim2DClassInfo = (function () {
-        function Prim2DClassInfo() {
-        }
-        return Prim2DClassInfo;
-    }());
-    BABYLON.Prim2DClassInfo = Prim2DClassInfo;
-    var Prim2DPropInfo = (function () {
-        function Prim2DPropInfo() {
-        }
-        Prim2DPropInfo.PROPKIND_MODEL = 1;
-        Prim2DPropInfo.PROPKIND_INSTANCE = 2;
-        Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
-        return Prim2DPropInfo;
-    }());
-    BABYLON.Prim2DPropInfo = Prim2DPropInfo;
-    var PropertyChangedInfo = (function () {
-        function PropertyChangedInfo() {
-        }
-        return PropertyChangedInfo;
-    }());
-    BABYLON.PropertyChangedInfo = PropertyChangedInfo;
-    var ClassTreeInfo = (function () {
-        function ClassTreeInfo(baseClass, type, classContentFactory) {
-            this._baseClass = baseClass;
-            this._type = type;
-            this._subClasses = new Array();
-            this._levelContent = new BABYLON.StringDictionary();
-            this._classContentFactory = classContentFactory;
-        }
-        Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
-            get: function () {
-                if (!this._classContent) {
-                    this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
-                }
-                return this._classContent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ClassTreeInfo.prototype, "type", {
-            get: function () {
-                return this._type;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
-            get: function () {
-                return this._levelContent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
-            get: function () {
-                if (!this._fullContent) {
-                    var dic_1 = new BABYLON.StringDictionary();
-                    var curLevel = this;
-                    while (curLevel) {
-                        curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
-                        curLevel = curLevel._baseClass;
-                    }
-                    this._fullContent = dic_1;
-                }
-                return this._fullContent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ClassTreeInfo.prototype.getLevelOf = function (type) {
-            // Are we already there?
-            if (type === this._type) {
-                return this;
-            }
-            var baseProto = Object.getPrototypeOf(type);
-            var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
-            if (!curProtoContent) {
-                this.getLevelOf(baseProto);
-            }
-            return this.getOrAddType(baseProto, type);
-        };
-        ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
-            // Are we at the level corresponding to the baseType?
-            // If so, get or add the level we're looking for
-            if (baseType === this._type) {
-                for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
-                    var subType = _a[_i];
-                    if (subType.type === type) {
-                        return subType.node;
-                    }
-                }
-                var node = new ClassTreeInfo(this, type, this._classContentFactory);
-                var info = { type: type, node: node };
-                this._subClasses.push(info);
-                return info.node;
-            }
-            // Recurse down to keep looking for the node corresponding to the baseTypeName
-            for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
-                var subType = _c[_b];
-                var info = subType.node.getOrAddType(baseType, type);
-                if (info) {
-                    return info;
-                }
-            }
-            return null;
-        };
-        ClassTreeInfo.get = function (type) {
-            var dic = type["__classTreeInfo"];
-            if (!dic) {
-                return null;
-            }
-            return dic.getLevelOf(type);
-        };
-        ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
-            var dic = type["__classTreeInfo"];
-            if (!dic) {
-                dic = new ClassTreeInfo(null, type, classContentFactory);
-                type["__classTreeInfo"] = dic;
-            }
-            return dic;
-        };
-        return ClassTreeInfo;
-    }());
-    BABYLON.ClassTreeInfo = ClassTreeInfo;
-    var SmartPropertyPrim = (function () {
-        function SmartPropertyPrim() {
-            this._flags = 0;
-            this._modelKey = null;
-            this._instanceDirtyFlags = 0;
-            this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
-            this.animations = new Array();
-        }
-        Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
-            /**
-             * Check if the object is disposed or not.
-             * @returns true if the object is dispose, false otherwise.
-             */
-            get: function () {
-                return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
-         * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
-         */
-        SmartPropertyPrim.prototype.dispose = function () {
-            if (this.isDisposed) {
-                return false;
-            }
-            // Don't set to null, it may upset somebody...
-            this.animations.splice(0);
-            this._setFlags(SmartPropertyPrim.flagIsDisposed);
-            return true;
-        };
-        /**
-         * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
-         * Look at Sprite2D for more information
-         */
-        SmartPropertyPrim.prototype.getAnimatables = function () {
-            return new Array();
-        };
-        Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
-            /**
-             * Property giving the Model Key associated to the property.
-             * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
-             * @returns the model key string.
-             */
-            get: function () {
-                var _this = this;
-                // No need to compute it?
-                if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
-                    return this._modelKey;
-                }
-                var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
-                var propDic = this.propDic;
-                propDic.forEach(function (k, v) {
-                    if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
-                        var propVal = _this[v.name];
-                        // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
-                        if (propVal && propVal.constructor === Array) {
-                            var firstVal = propVal[0];
-                            if (!firstVal) {
-                                propVal = 0;
-                            }
-                            else {
-                                propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
-                            }
-                        }
-                        modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
-                    }
-                });
-                this._clearFlags(SmartPropertyPrim.flagModelDirty);
-                this._modelKey = modelKey;
-                return modelKey;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
-            /**
-             * States if the Primitive is dirty and should be rendered again next time.
-             * @returns true is dirty, false otherwise
-             */
-            get: function () {
-                return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
-            /**
-             * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
-             * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
-             */
-            get: function () {
-                if (!this._propInfo) {
-                    var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
-                    if (!cti) {
-                        throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
-                    }
-                    this._propInfo = cti.fullContent;
-                }
-                return this._propInfo;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
-            var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
-            var node = dic.getLevelOf(target);
-            var propInfo = node.levelContent.get(propId.toString());
-            if (propInfo) {
-                throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
-            }
-            // Create, setup and add the PropInfo object to our prop dictionary
-            propInfo = new Prim2DPropInfo();
-            propInfo.id = propId;
-            propInfo.flagId = Math.pow(2, propId);
-            propInfo.kind = kind;
-            propInfo.name = propName;
-            propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
-            propInfo.typeLevelCompare = typeLevelCompare;
-            node.levelContent.add(propName, propInfo);
-            return propInfo;
-        };
-        SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
-            // Nothing to nothing: nothing to do!
-            if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
-                return true;
-            }
-            // Check value unchanged
-            if ((curValue != null) && (newValue != null)) {
-                if (typeof (curValue.equals) == "function") {
-                    if (curValue.equals(newValue)) {
-                        return true;
-                    }
-                }
-                else {
-                    if (curValue === newValue) {
-                        return true;
-                    }
-                }
-            }
-            return false;
-        };
-        SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
-            if (this.isDisposed) {
-                return;
-            }
-            var i = propertyName.indexOf(".");
-            if (i !== -1) {
-                propertyName = propertyName.substr(0, i);
-            }
-            var propInfo = this.propDic.get(propertyName);
-            if (!propInfo) {
-                return;
-            }
-            var newValue = this[propertyName];
-            this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
-        };
-        SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
-            // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
-            if (propInfo.dirtyBoundingInfo) {
-                this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
-                // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
-                if (this instanceof BABYLON.Prim2DBase) {
-                    var curprim = this.parent;
-                    while (curprim) {
-                        curprim._boundingInfoDirty = true;
-                        if (curprim instanceof BABYLON.Group2D) {
-                            if (curprim.isRenderableGroup) {
-                                break;
-                            }
-                        }
-                        curprim = curprim.parent;
-                    }
-                }
-            }
-            // Trigger property changed
-            var info = SmartPropertyPrim.propChangedInfo;
-            info.oldValue = curValue;
-            info.newValue = newValue;
-            info.propertyName = propName;
-            var propMask = propInfo.flagId;
-            this.propertyChanged.notifyObservers(info, propMask);
-            // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
-            if (this instanceof BABYLON.Group2D) {
-                this.handleGroupChanged(propInfo);
-            }
-            // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
-            var instanceDirty = false;
-            if (typeLevelCompare && curValue != null && newValue != null) {
-                var cvProto = curValue.__proto__;
-                var nvProto = newValue.__proto__;
-                instanceDirty = (cvProto === nvProto);
-            }
-            // Set the dirty flags
-            if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
-                this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
-            }
-            else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
-                this.onPrimitivePropertyDirty(propMask);
-            }
-        };
-        SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
-            if (!this.isDirty) {
-                this.onPrimBecomesDirty();
-            }
-            this._instanceDirtyFlags |= propFlagId;
-        };
-        SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
-        };
-        /**
-         * Check if a given set of properties are dirty or not.
-         * @param flags a ORed combination of Prim2DPropInfo.flagId values
-         * @return true if at least one property is dirty, false if none of them are.
-         */
-        SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
-            return (this._instanceDirtyFlags & flags) !== 0;
-        };
-        /**
-         * Clear a given set of properties.
-         * @param flags a ORed combination of Prim2DPropInfo.flagId values
-         * @return the new set of property still marked as dirty
-         */
-        SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
-            this._instanceDirtyFlags &= ~flags;
-            return this._instanceDirtyFlags;
-        };
-        SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
-            this._instanceDirtyFlags = 0;
-        };
-        Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
-            /**
-             * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
-             * @returns {}
-             */
-            get: function () {
-                if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
-                    this.updateLevelBoundingInfo();
-                    this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
-                }
-                return this._levelBoundingInfo;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * This method must be overridden by a given Primitive implementation to compute its boundingInfo
-         */
-        SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
-        };
-        /**
-         * Property method called when the Primitive becomes dirty
-         */
-        SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
-        };
-        SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
-            return function (target, propName, descriptor) {
-                var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
-                if (piStore) {
-                    piStore(propInfo);
-                }
-                var getter = descriptor.get, setter = descriptor.set;
-                // Overload the property setter implementation to add our own logic
-                descriptor.set = function (val) {
-                    // check for disposed first, do nothing
-                    if (this.isDisposed) {
-                        return;
-                    }
-                    var curVal = getter.call(this);
-                    if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
-                        return;
-                    }
-                    // Cast the object we're working one
-                    var prim = this;
-                    // Change the value
-                    setter.call(this, val);
-                    // Notify change, dirty flags update
-                    prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
-                };
-            };
-        };
-        /**
-         * Add an externally attached data from its key.
-         * This method call will fail and return false, if such key already exists.
-         * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
-         * @param key the unique key that identifies the data
-         * @param data the data object to associate to the key for this Engine instance
-         * @return true if no such key were already present and the data was added successfully, false otherwise
-         */
-        SmartPropertyPrim.prototype.addExternalData = function (key, data) {
-            if (!this._externalData) {
-                this._externalData = new BABYLON.StringDictionary();
-            }
-            return this._externalData.add(key, data);
-        };
-        /**
-         * Get an externally attached data from its key
-         * @param key the unique key that identifies the data
-         * @return the associated data, if present (can be null), or undefined if not present
-         */
-        SmartPropertyPrim.prototype.getExternalData = function (key) {
-            if (!this._externalData) {
-                return null;
-            }
-            return this._externalData.get(key);
-        };
-        /**
-         * Get an externally attached data from its key, create it using a factory if it's not already present
-         * @param key the unique key that identifies the data
-         * @param factory the factory that will be called to create the instance if and only if it doesn't exists
-         * @return the associated data, can be null if the factory returned null.
-         */
-        SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
-            if (!this._externalData) {
-                this._externalData = new BABYLON.StringDictionary();
-            }
-            return this._externalData.getOrAddWithFactory(key, factory);
-        };
-        /**
-         * Remove an externally attached data from the Engine instance
-         * @param key the unique key that identifies the data
-         * @return true if the data was successfully removed, false if it doesn't exist
-         */
-        SmartPropertyPrim.prototype.removeExternalData = function (key) {
-            if (!this._externalData) {
-                return false;
-            }
-            return this._externalData.remove(key);
-        };
-        SmartPropertyPrim.prototype._isFlagSet = function (flag) {
-            return (this._flags & flag) !== 0;
-        };
-        SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
-            return (this._flags & flags) === flags;
-        };
-        SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
-            return (this._flags & flags) !== 0;
-        };
-        SmartPropertyPrim.prototype._clearFlags = function (flags) {
-            this._flags &= ~flags;
-        };
-        SmartPropertyPrim.prototype._setFlags = function (flags) {
-            var cur = this._flags;
-            this._flags |= flags;
-            return cur;
-        };
-        SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
-            if (state) {
-                this._flags |= flags;
-            }
-            else {
-                this._flags &= ~flags;
-            }
-        };
-        SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
-        SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
-        SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
-        SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
-        SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
-        SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
-        SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
-        SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
-        SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
-        SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
-        SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
-        SmartPropertyPrim = __decorate([
-            BABYLON.className("SmartPropertyPrim")
-        ], SmartPropertyPrim);
-        return SmartPropertyPrim;
-    }());
-    BABYLON.SmartPropertyPrim = SmartPropertyPrim;
-    function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
-        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
-        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
-        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
-    }
-    BABYLON.modelLevelProperty = modelLevelProperty;
-    function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
-        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
-        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
-        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
-    }
-    BABYLON.instanceLevelProperty = instanceLevelProperty;
-    function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
-        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
-        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
-        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
-    }
-    BABYLON.dynamicLevelProperty = dynamicLevelProperty;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.smartPropertyPrim.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Prim2DClassInfo = (function () {
+        function Prim2DClassInfo() {
+        }
+        return Prim2DClassInfo;
+    })();
+    BABYLON.Prim2DClassInfo = Prim2DClassInfo;
+    var Prim2DPropInfo = (function () {
+        function Prim2DPropInfo() {
+        }
+        Prim2DPropInfo.PROPKIND_MODEL = 1;
+        Prim2DPropInfo.PROPKIND_INSTANCE = 2;
+        Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
+        return Prim2DPropInfo;
+    })();
+    BABYLON.Prim2DPropInfo = Prim2DPropInfo;
+    var PropertyChangedInfo = (function () {
+        function PropertyChangedInfo() {
+        }
+        return PropertyChangedInfo;
+    })();
+    BABYLON.PropertyChangedInfo = PropertyChangedInfo;
+    var ClassTreeInfo = (function () {
+        function ClassTreeInfo(baseClass, type, classContentFactory) {
+            this._baseClass = baseClass;
+            this._type = type;
+            this._subClasses = new Array();
+            this._levelContent = new BABYLON.StringDictionary();
+            this._classContentFactory = classContentFactory;
+        }
+        Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
+            get: function () {
+                if (!this._classContent) {
+                    this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
+                }
+                return this._classContent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ClassTreeInfo.prototype, "type", {
+            get: function () {
+                return this._type;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
+            get: function () {
+                return this._levelContent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
+            get: function () {
+                if (!this._fullContent) {
+                    var dic = new BABYLON.StringDictionary();
+                    var curLevel = this;
+                    while (curLevel) {
+                        curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
+                        curLevel = curLevel._baseClass;
+                    }
+                    this._fullContent = dic;
+                }
+                return this._fullContent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ClassTreeInfo.prototype.getLevelOf = function (type) {
+            // Are we already there?
+            if (type === this._type) {
+                return this;
+            }
+            var baseProto = Object.getPrototypeOf(type);
+            var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
+            if (!curProtoContent) {
+                this.getLevelOf(baseProto);
+            }
+            return this.getOrAddType(baseProto, type);
+        };
+        ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
+            // Are we at the level corresponding to the baseType?
+            // If so, get or add the level we're looking for
+            if (baseType === this._type) {
+                for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
+                    var subType = _a[_i];
+                    if (subType.type === type) {
+                        return subType.node;
+                    }
+                }
+                var node = new ClassTreeInfo(this, type, this._classContentFactory);
+                var info = { type: type, node: node };
+                this._subClasses.push(info);
+                return info.node;
+            }
+            // Recurse down to keep looking for the node corresponding to the baseTypeName
+            for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
+                var subType = _c[_b];
+                var info = subType.node.getOrAddType(baseType, type);
+                if (info) {
+                    return info;
+                }
+            }
+            return null;
+        };
+        ClassTreeInfo.get = function (type) {
+            var dic = type["__classTreeInfo"];
+            if (!dic) {
+                return null;
+            }
+            return dic.getLevelOf(type);
+        };
+        ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
+            var dic = type["__classTreeInfo"];
+            if (!dic) {
+                dic = new ClassTreeInfo(null, type, classContentFactory);
+                type["__classTreeInfo"] = dic;
+            }
+            return dic;
+        };
+        return ClassTreeInfo;
+    })();
+    BABYLON.ClassTreeInfo = ClassTreeInfo;
+    var SmartPropertyPrim = (function () {
+        function SmartPropertyPrim() {
+        }
+        SmartPropertyPrim.prototype.setupSmartPropertyPrim = function () {
+            this._modelKey = null;
+            this._modelDirty = false;
+            this._levelBoundingInfoDirty = false;
+            this._instanceDirtyFlags = 0;
+            this._isDisposed = false;
+            this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
+            this.animations = new Array();
+        };
+        Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
+            /**
+             * Check if the object is disposed or not.
+             * @returns true if the object is dispose, false otherwise.
+             */
+            get: function () {
+                return this._isDisposed;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
+         * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
+         */
+        SmartPropertyPrim.prototype.dispose = function () {
+            if (this.isDisposed) {
+                return false;
+            }
+            // Don't set to null, it may upset somebody...
+            this.animations.splice(0);
+            this._isDisposed = true;
+            return true;
+        };
+        /**
+         * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
+         * Look at Sprite2D for more information
+         */
+        SmartPropertyPrim.prototype.getAnimatables = function () {
+            return new Array();
+        };
+        Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
+            /**
+             * Property giving the Model Key associated to the property.
+             * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
+             * @returns the model key string.
+             */
+            get: function () {
+                var _this = this;
+                // No need to compute it?
+                if (!this._modelDirty && this._modelKey) {
+                    return this._modelKey;
+                }
+                var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
+                var propDic = this.propDic;
+                propDic.forEach(function (k, v) {
+                    if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
+                        var propVal = _this[v.name];
+                        // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
+                        if (propVal && propVal.constructor === Array) {
+                            var firstVal = propVal[0];
+                            if (!firstVal) {
+                                propVal = 0;
+                            }
+                            else {
+                                propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
+                            }
+                        }
+                        modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
+                    }
+                });
+                this._modelDirty = false;
+                this._modelKey = modelKey;
+                return modelKey;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
+            /**
+             * States if the Primitive is dirty and should be rendered again next time.
+             * @returns true is dirty, false otherwise
+             */
+            get: function () {
+                return (this._instanceDirtyFlags !== 0) || this._modelDirty;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
+            /**
+             * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
+             * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
+             */
+            get: function () {
+                if (!this._propInfo) {
+                    var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
+                    if (!cti) {
+                        throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
+                    }
+                    this._propInfo = cti.fullContent;
+                }
+                return this._propInfo;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
+            var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
+            var node = dic.getLevelOf(target);
+            var propInfo = node.levelContent.get(propId.toString());
+            if (propInfo) {
+                throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
+            }
+            // Create, setup and add the PropInfo object to our prop dictionary
+            propInfo = new Prim2DPropInfo();
+            propInfo.id = propId;
+            propInfo.flagId = Math.pow(2, propId);
+            propInfo.kind = kind;
+            propInfo.name = propName;
+            propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
+            propInfo.typeLevelCompare = typeLevelCompare;
+            node.levelContent.add(propName, propInfo);
+            return propInfo;
+        };
+        SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
+            // Nothing to nothing: nothing to do!
+            if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
+                return true;
+            }
+            // Check value unchanged
+            if ((curValue != null) && (newValue != null)) {
+                if (typeof (curValue.equals) == "function") {
+                    if (curValue.equals(newValue)) {
+                        return true;
+                    }
+                }
+                else {
+                    if (curValue === newValue) {
+                        return true;
+                    }
+                }
+            }
+            return false;
+        };
+        SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
+            if (this.isDisposed) {
+                return;
+            }
+            var i = propertyName.indexOf(".");
+            if (i !== -1) {
+                propertyName = propertyName.substr(0, i);
+            }
+            var propInfo = this.propDic.get(propertyName);
+            if (!propInfo) {
+                return;
+            }
+            var newValue = this[propertyName];
+            this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
+        };
+        SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
+            // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
+            if (propInfo.dirtyBoundingInfo) {
+                this._levelBoundingInfoDirty = true;
+                // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
+                if (this instanceof BABYLON.Prim2DBase) {
+                    var curprim = this.parent;
+                    while (curprim) {
+                        curprim._boundingInfoDirty = true;
+                        if (curprim instanceof BABYLON.Group2D) {
+                            if (curprim.isRenderableGroup) {
+                                break;
+                            }
+                        }
+                        curprim = curprim.parent;
+                    }
+                }
+            }
+            // Trigger property changed
+            var info = SmartPropertyPrim.propChangedInfo;
+            info.oldValue = curValue;
+            info.newValue = newValue;
+            info.propertyName = propName;
+            var propMask = propInfo.flagId;
+            this.propertyChanged.notifyObservers(info, propMask);
+            // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
+            if (this instanceof BABYLON.Group2D) {
+                this.handleGroupChanged(propInfo);
+            }
+            // Check if we need to dirty only if the type change and make the test
+            var skipDirty = false;
+            if (typeLevelCompare && curValue != null && newValue != null) {
+                var cvProto = curValue.__proto__;
+                var nvProto = newValue.__proto__;
+                skipDirty = (cvProto === nvProto);
+            }
+            // Set the dirty flags
+            if (!skipDirty) {
+                if (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL) {
+                    if (!this.isDirty) {
+                        this.onPrimBecomesDirty();
+                    }
+                    this._modelDirty = true;
+                }
+                else if ((propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
+                    if (!this.isDirty) {
+                        this.onPrimBecomesDirty();
+                    }
+                    this._instanceDirtyFlags |= propMask;
+                }
+            }
+        };
+        SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
+        };
+        /**
+         * Check if a given set of properties are dirty or not.
+         * @param flags a ORed combination of Prim2DPropInfo.flagId values
+         * @return true if at least one property is dirty, false if none of them are.
+         */
+        SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
+            return (this._instanceDirtyFlags & flags) !== 0;
+        };
+        /**
+         * Clear a given set of properties.
+         * @param flags a ORed combination of Prim2DPropInfo.flagId values
+         * @return the new set of property still marked as dirty
+         */
+        SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
+            this._instanceDirtyFlags &= ~flags;
+            return this._instanceDirtyFlags;
+        };
+        SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
+            this._instanceDirtyFlags = 0;
+        };
+        Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
+            /**
+             * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
+             * @returns {}
+             */
+            get: function () {
+                if (this._levelBoundingInfoDirty) {
+                    this.updateLevelBoundingInfo();
+                    this._levelBoundingInfoDirty = false;
+                }
+                return this._levelBoundingInfo;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * This method must be overridden by a given Primitive implementation to compute its boundingInfo
+         */
+        SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
+        };
+        /**
+         * Property method called when the Primitive becomes dirty
+         */
+        SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
+        };
+        SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
+            return function (target, propName, descriptor) {
+                var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
+                if (piStore) {
+                    piStore(propInfo);
+                }
+                var getter = descriptor.get, setter = descriptor.set;
+                // Overload the property setter implementation to add our own logic
+                descriptor.set = function (val) {
+                    // check for disposed first, do nothing
+                    if (this.isDisposed) {
+                        return;
+                    }
+                    var curVal = getter.call(this);
+                    if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
+                        return;
+                    }
+                    // Cast the object we're working one
+                    var prim = this;
+                    // Change the value
+                    setter.call(this, val);
+                    // Notify change, dirty flags update
+                    prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
+                };
+            };
+        };
+        SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
+        SmartPropertyPrim = __decorate([
+            BABYLON.className("SmartPropertyPrim")
+        ], SmartPropertyPrim);
+        return SmartPropertyPrim;
+    })();
+    BABYLON.SmartPropertyPrim = SmartPropertyPrim;
+    function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
+        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
+        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
+        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
+    }
+    BABYLON.modelLevelProperty = modelLevelProperty;
+    function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
+        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
+        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
+        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
+    }
+    BABYLON.instanceLevelProperty = instanceLevelProperty;
+    function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
+        if (typeLevelCompare === void 0) { typeLevelCompare = false; }
+        if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
+        return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
+    }
+    BABYLON.dynamicLevelProperty = dynamicLevelProperty;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 355 - 339
src/Canvas2d/babylon.sprite2d.js


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 390 - 395
src/Canvas2d/babylon.text2d.js


+ 27 - 28
src/Canvas2d/babylon.worldSpaceCanvas2d.js

@@ -1,28 +1,27 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This is the class that is used to display a World Space Canvas into a scene
-     */
-    var WorldSpaceCanvas2D = (function (_super) {
-        __extends(WorldSpaceCanvas2D, _super);
-        function WorldSpaceCanvas2D(name, scene, canvas) {
-            _super.call(this, name, scene);
-            this._canvas = canvas;
-        }
-        WorldSpaceCanvas2D.prototype.dispose = function () {
-            _super.prototype.dispose.call(this);
-            if (this._canvas) {
-                this._canvas.dispose();
-                this._canvas = null;
-            }
-        };
-        return WorldSpaceCanvas2D;
-    }(BABYLON.Mesh));
-    BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.worldSpaceCanvas2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This is the class that is used to display a World Space Canvas into a scene
+     */
+    var WorldSpaceCanvas2D = (function (_super) {
+        __extends(WorldSpaceCanvas2D, _super);
+        function WorldSpaceCanvas2D(name, scene, canvas) {
+            _super.call(this, name, scene);
+            this._canvas = canvas;
+        }
+        WorldSpaceCanvas2D.prototype.dispose = function () {
+            _super.prototype.dispose.call(this);
+            if (this._canvas) {
+                this._canvas.dispose();
+                this._canvas = null;
+            }
+        };
+        return WorldSpaceCanvas2D;
+    })(BABYLON.Mesh);
+    BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
+})(BABYLON || (BABYLON = {}));

+ 272 - 273
src/Collisions/babylon.collider.js

@@ -1,273 +1,272 @@
-var BABYLON;
-(function (BABYLON) {
-    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
-        if (boxMin.x > sphereCenter.x + sphereRadius)
-            return false;
-        if (sphereCenter.x - sphereRadius > boxMax.x)
-            return false;
-        if (boxMin.y > sphereCenter.y + sphereRadius)
-            return false;
-        if (sphereCenter.y - sphereRadius > boxMax.y)
-            return false;
-        if (boxMin.z > sphereCenter.z + sphereRadius)
-            return false;
-        if (sphereCenter.z - sphereRadius > boxMax.z)
-            return false;
-        return true;
-    };
-    var getLowestRoot = function (a, b, c, maxR) {
-        var determinant = b * b - 4.0 * a * c;
-        var result = { root: 0, found: false };
-        if (determinant < 0)
-            return result;
-        var sqrtD = Math.sqrt(determinant);
-        var r1 = (-b - sqrtD) / (2.0 * a);
-        var r2 = (-b + sqrtD) / (2.0 * a);
-        if (r1 > r2) {
-            var temp = r2;
-            r2 = r1;
-            r1 = temp;
-        }
-        if (r1 > 0 && r1 < maxR) {
-            result.root = r1;
-            result.found = true;
-            return result;
-        }
-        if (r2 > 0 && r2 < maxR) {
-            result.root = r2;
-            result.found = true;
-            return result;
-        }
-        return result;
-    };
-    var Collider = (function () {
-        function Collider() {
-            this.radius = new BABYLON.Vector3(1, 1, 1);
-            this.retry = 0;
-            this.basePointWorld = BABYLON.Vector3.Zero();
-            this.velocityWorld = BABYLON.Vector3.Zero();
-            this.normalizedVelocity = BABYLON.Vector3.Zero();
-            this._collisionPoint = BABYLON.Vector3.Zero();
-            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
-            this._tempVector = BABYLON.Vector3.Zero();
-            this._tempVector2 = BABYLON.Vector3.Zero();
-            this._tempVector3 = BABYLON.Vector3.Zero();
-            this._tempVector4 = BABYLON.Vector3.Zero();
-            this._edge = BABYLON.Vector3.Zero();
-            this._baseToVertex = BABYLON.Vector3.Zero();
-            this._destinationPoint = BABYLON.Vector3.Zero();
-            this._slidePlaneNormal = BABYLON.Vector3.Zero();
-            this._displacementVector = BABYLON.Vector3.Zero();
-        }
-        // Methods
-        Collider.prototype._initialize = function (source, dir, e) {
-            this.velocity = dir;
-            BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
-            this.basePoint = source;
-            source.multiplyToRef(this.radius, this.basePointWorld);
-            dir.multiplyToRef(this.radius, this.velocityWorld);
-            this.velocityWorldLength = this.velocityWorld.length();
-            this.epsilon = e;
-            this.collisionFound = false;
-        };
-        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
-            pa.subtractToRef(point, this._tempVector);
-            pb.subtractToRef(point, this._tempVector2);
-            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
-            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            if (d < 0)
-                return false;
-            pc.subtractToRef(point, this._tempVector3);
-            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
-            d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            if (d < 0)
-                return false;
-            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
-            d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            return d >= 0;
-        };
-        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
-            var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
-            var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
-            if (distance > this.velocityWorldLength + max + sphereRadius) {
-                return false;
-            }
-            if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
-                return false;
-            return true;
-        };
-        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
-            var t0;
-            var embeddedInPlane = false;
-            //defensive programming, actually not needed.
-            if (!trianglePlaneArray) {
-                trianglePlaneArray = [];
-            }
-            if (!trianglePlaneArray[faceIndex]) {
-                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
-                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
-            }
-            var trianglePlane = trianglePlaneArray[faceIndex];
-            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
-                return;
-            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
-            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
-            if (normalDotVelocity == 0) {
-                if (Math.abs(signedDistToTrianglePlane) >= 1.0)
-                    return;
-                embeddedInPlane = true;
-                t0 = 0;
-            }
-            else {
-                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
-                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
-                if (t0 > t1) {
-                    var temp = t1;
-                    t1 = t0;
-                    t0 = temp;
-                }
-                if (t0 > 1.0 || t1 < 0.0)
-                    return;
-                if (t0 < 0)
-                    t0 = 0;
-                if (t0 > 1.0)
-                    t0 = 1.0;
-            }
-            this._collisionPoint.copyFromFloats(0, 0, 0);
-            var found = false;
-            var t = 1.0;
-            if (!embeddedInPlane) {
-                this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
-                this.velocity.scaleToRef(t0, this._tempVector);
-                this._planeIntersectionPoint.addInPlace(this._tempVector);
-                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
-                    found = true;
-                    t = t0;
-                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
-                }
-            }
-            if (!found) {
-                var velocitySquaredLength = this.velocity.lengthSquared();
-                var a = velocitySquaredLength;
-                this.basePoint.subtractToRef(p1, this._tempVector);
-                var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                var c = this._tempVector.lengthSquared() - 1.0;
-                var lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p1);
-                }
-                this.basePoint.subtractToRef(p2, this._tempVector);
-                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                c = this._tempVector.lengthSquared() - 1.0;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p2);
-                }
-                this.basePoint.subtractToRef(p3, this._tempVector);
-                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                c = this._tempVector.lengthSquared() - 1.0;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p3);
-                }
-                p2.subtractToRef(p1, this._edge);
-                p1.subtractToRef(this.basePoint, this._baseToVertex);
-                var edgeSquaredLength = this._edge.lengthSquared();
-                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p1.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-                p3.subtractToRef(p2, this._edge);
-                p2.subtractToRef(this.basePoint, this._baseToVertex);
-                edgeSquaredLength = this._edge.lengthSquared();
-                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p2.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-                p1.subtractToRef(p3, this._edge);
-                p3.subtractToRef(this.basePoint, this._baseToVertex);
-                edgeSquaredLength = this._edge.lengthSquared();
-                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p3.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-            }
-            if (found) {
-                var distToCollision = t * this.velocity.length();
-                if (!this.collisionFound || distToCollision < this.nearestDistance) {
-                    if (!this.intersectionPoint) {
-                        this.intersectionPoint = this._collisionPoint.clone();
-                    }
-                    else {
-                        this.intersectionPoint.copyFrom(this._collisionPoint);
-                    }
-                    this.nearestDistance = distToCollision;
-                    this.collisionFound = true;
-                }
-            }
-        };
-        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
-            for (var i = indexStart; i < indexEnd; i += 3) {
-                var p1 = pts[indices[i] - decal];
-                var p2 = pts[indices[i + 1] - decal];
-                var p3 = pts[indices[i + 2] - decal];
-                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
-            }
-        };
-        Collider.prototype._getResponse = function (pos, vel) {
-            pos.addToRef(vel, this._destinationPoint);
-            vel.scaleInPlace((this.nearestDistance / vel.length()));
-            this.basePoint.addToRef(vel, pos);
-            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
-            this._slidePlaneNormal.normalize();
-            this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
-            pos.addInPlace(this._displacementVector);
-            this.intersectionPoint.addInPlace(this._displacementVector);
-            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
-            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
-            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
-        };
-        return Collider;
-    }());
-    BABYLON.Collider = Collider;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.collider.js.map
+var BABYLON;
+(function (BABYLON) {
+    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
+        if (boxMin.x > sphereCenter.x + sphereRadius)
+            return false;
+        if (sphereCenter.x - sphereRadius > boxMax.x)
+            return false;
+        if (boxMin.y > sphereCenter.y + sphereRadius)
+            return false;
+        if (sphereCenter.y - sphereRadius > boxMax.y)
+            return false;
+        if (boxMin.z > sphereCenter.z + sphereRadius)
+            return false;
+        if (sphereCenter.z - sphereRadius > boxMax.z)
+            return false;
+        return true;
+    };
+    var getLowestRoot = function (a, b, c, maxR) {
+        var determinant = b * b - 4.0 * a * c;
+        var result = { root: 0, found: false };
+        if (determinant < 0)
+            return result;
+        var sqrtD = Math.sqrt(determinant);
+        var r1 = (-b - sqrtD) / (2.0 * a);
+        var r2 = (-b + sqrtD) / (2.0 * a);
+        if (r1 > r2) {
+            var temp = r2;
+            r2 = r1;
+            r1 = temp;
+        }
+        if (r1 > 0 && r1 < maxR) {
+            result.root = r1;
+            result.found = true;
+            return result;
+        }
+        if (r2 > 0 && r2 < maxR) {
+            result.root = r2;
+            result.found = true;
+            return result;
+        }
+        return result;
+    };
+    var Collider = (function () {
+        function Collider() {
+            this.radius = new BABYLON.Vector3(1, 1, 1);
+            this.retry = 0;
+            this.basePointWorld = BABYLON.Vector3.Zero();
+            this.velocityWorld = BABYLON.Vector3.Zero();
+            this.normalizedVelocity = BABYLON.Vector3.Zero();
+            this._collisionPoint = BABYLON.Vector3.Zero();
+            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
+            this._tempVector = BABYLON.Vector3.Zero();
+            this._tempVector2 = BABYLON.Vector3.Zero();
+            this._tempVector3 = BABYLON.Vector3.Zero();
+            this._tempVector4 = BABYLON.Vector3.Zero();
+            this._edge = BABYLON.Vector3.Zero();
+            this._baseToVertex = BABYLON.Vector3.Zero();
+            this._destinationPoint = BABYLON.Vector3.Zero();
+            this._slidePlaneNormal = BABYLON.Vector3.Zero();
+            this._displacementVector = BABYLON.Vector3.Zero();
+        }
+        // Methods
+        Collider.prototype._initialize = function (source, dir, e) {
+            this.velocity = dir;
+            BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
+            this.basePoint = source;
+            source.multiplyToRef(this.radius, this.basePointWorld);
+            dir.multiplyToRef(this.radius, this.velocityWorld);
+            this.velocityWorldLength = this.velocityWorld.length();
+            this.epsilon = e;
+            this.collisionFound = false;
+        };
+        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
+            pa.subtractToRef(point, this._tempVector);
+            pb.subtractToRef(point, this._tempVector2);
+            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
+            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            if (d < 0)
+                return false;
+            pc.subtractToRef(point, this._tempVector3);
+            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
+            d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            if (d < 0)
+                return false;
+            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
+            d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            return d >= 0;
+        };
+        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
+            var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
+            var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
+            if (distance > this.velocityWorldLength + max + sphereRadius) {
+                return false;
+            }
+            if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
+                return false;
+            return true;
+        };
+        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
+            var t0;
+            var embeddedInPlane = false;
+            //defensive programming, actually not needed.
+            if (!trianglePlaneArray) {
+                trianglePlaneArray = [];
+            }
+            if (!trianglePlaneArray[faceIndex]) {
+                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
+                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
+            }
+            var trianglePlane = trianglePlaneArray[faceIndex];
+            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
+                return;
+            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
+            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
+            if (normalDotVelocity == 0) {
+                if (Math.abs(signedDistToTrianglePlane) >= 1.0)
+                    return;
+                embeddedInPlane = true;
+                t0 = 0;
+            }
+            else {
+                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
+                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
+                if (t0 > t1) {
+                    var temp = t1;
+                    t1 = t0;
+                    t0 = temp;
+                }
+                if (t0 > 1.0 || t1 < 0.0)
+                    return;
+                if (t0 < 0)
+                    t0 = 0;
+                if (t0 > 1.0)
+                    t0 = 1.0;
+            }
+            this._collisionPoint.copyFromFloats(0, 0, 0);
+            var found = false;
+            var t = 1.0;
+            if (!embeddedInPlane) {
+                this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
+                this.velocity.scaleToRef(t0, this._tempVector);
+                this._planeIntersectionPoint.addInPlace(this._tempVector);
+                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
+                    found = true;
+                    t = t0;
+                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
+                }
+            }
+            if (!found) {
+                var velocitySquaredLength = this.velocity.lengthSquared();
+                var a = velocitySquaredLength;
+                this.basePoint.subtractToRef(p1, this._tempVector);
+                var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                var c = this._tempVector.lengthSquared() - 1.0;
+                var lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p1);
+                }
+                this.basePoint.subtractToRef(p2, this._tempVector);
+                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                c = this._tempVector.lengthSquared() - 1.0;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p2);
+                }
+                this.basePoint.subtractToRef(p3, this._tempVector);
+                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                c = this._tempVector.lengthSquared() - 1.0;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p3);
+                }
+                p2.subtractToRef(p1, this._edge);
+                p1.subtractToRef(this.basePoint, this._baseToVertex);
+                var edgeSquaredLength = this._edge.lengthSquared();
+                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p1.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+                p3.subtractToRef(p2, this._edge);
+                p2.subtractToRef(this.basePoint, this._baseToVertex);
+                edgeSquaredLength = this._edge.lengthSquared();
+                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p2.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+                p1.subtractToRef(p3, this._edge);
+                p3.subtractToRef(this.basePoint, this._baseToVertex);
+                edgeSquaredLength = this._edge.lengthSquared();
+                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p3.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+            }
+            if (found) {
+                var distToCollision = t * this.velocity.length();
+                if (!this.collisionFound || distToCollision < this.nearestDistance) {
+                    if (!this.intersectionPoint) {
+                        this.intersectionPoint = this._collisionPoint.clone();
+                    }
+                    else {
+                        this.intersectionPoint.copyFrom(this._collisionPoint);
+                    }
+                    this.nearestDistance = distToCollision;
+                    this.collisionFound = true;
+                }
+            }
+        };
+        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
+            for (var i = indexStart; i < indexEnd; i += 3) {
+                var p1 = pts[indices[i] - decal];
+                var p2 = pts[indices[i + 1] - decal];
+                var p3 = pts[indices[i + 2] - decal];
+                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
+            }
+        };
+        Collider.prototype._getResponse = function (pos, vel) {
+            pos.addToRef(vel, this._destinationPoint);
+            vel.scaleInPlace((this.nearestDistance / vel.length()));
+            this.basePoint.addToRef(vel, pos);
+            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
+            this._slidePlaneNormal.normalize();
+            this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
+            pos.addInPlace(this._displacementVector);
+            this.intersectionPoint.addInPlace(this._displacementVector);
+            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
+            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
+            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
+        };
+        return Collider;
+    })();
+    BABYLON.Collider = Collider;
+})(BABYLON || (BABYLON = {}));

+ 273 - 274
src/Collisions/babylon.collisionCoordinator.js

@@ -1,274 +1,273 @@
-var BABYLON;
-(function (BABYLON) {
-    //WebWorker code will be inserted to this variable.
-    BABYLON.CollisionWorker = "";
-    (function (WorkerTaskType) {
-        WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
-        WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
-        WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
-    })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
-    var WorkerTaskType = BABYLON.WorkerTaskType;
-    (function (WorkerReplyType) {
-        WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
-        WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
-    })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
-    var WorkerReplyType = BABYLON.WorkerReplyType;
-    var CollisionCoordinatorWorker = (function () {
-        function CollisionCoordinatorWorker() {
-            var _this = this;
-            this._scaledPosition = BABYLON.Vector3.Zero();
-            this._scaledVelocity = BABYLON.Vector3.Zero();
-            this.onMeshUpdated = function (mesh) {
-                _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
-            };
-            this.onGeometryUpdated = function (geometry) {
-                _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
-            };
-            this._afterRender = function () {
-                if (!_this._init)
-                    return;
-                if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
-                    return;
-                }
-                //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
-                //TODO make sure update runs as fast as possible to be able to update 60 FPS.
-                if (_this._runningUpdated > 4) {
-                    return;
-                }
-                ++_this._runningUpdated;
-                var payload = {
-                    updatedMeshes: _this._addUpdateMeshesList,
-                    updatedGeometries: _this._addUpdateGeometriesList,
-                    removedGeometries: _this._toRemoveGeometryArray,
-                    removedMeshes: _this._toRemoveMeshesArray
-                };
-                var message = {
-                    payload: payload,
-                    taskType: WorkerTaskType.UPDATE
-                };
-                var serializable = [];
-                for (var id in payload.updatedGeometries) {
-                    if (payload.updatedGeometries.hasOwnProperty(id)) {
-                        //prepare transferables
-                        serializable.push(message.payload.updatedGeometries[id].indices.buffer);
-                        serializable.push(message.payload.updatedGeometries[id].normals.buffer);
-                        serializable.push(message.payload.updatedGeometries[id].positions.buffer);
-                    }
-                }
-                _this._worker.postMessage(message, serializable);
-                _this._addUpdateMeshesList = {};
-                _this._addUpdateGeometriesList = {};
-                _this._toRemoveGeometryArray = [];
-                _this._toRemoveMeshesArray = [];
-            };
-            this._onMessageFromWorker = function (e) {
-                var returnData = e.data;
-                if (returnData.error != WorkerReplyType.SUCCESS) {
-                    //TODO what errors can be returned from the worker?
-                    BABYLON.Tools.Warn("error returned from worker!");
-                    return;
-                }
-                switch (returnData.taskType) {
-                    case WorkerTaskType.INIT:
-                        _this._init = true;
-                        //Update the worked with ALL of the scene's current state
-                        _this._scene.meshes.forEach(function (mesh) {
-                            _this.onMeshAdded(mesh);
-                        });
-                        _this._scene.getGeometries().forEach(function (geometry) {
-                            _this.onGeometryAdded(geometry);
-                        });
-                        break;
-                    case WorkerTaskType.UPDATE:
-                        _this._runningUpdated--;
-                        break;
-                    case WorkerTaskType.COLLIDE:
-                        _this._runningCollisionTask = false;
-                        var returnPayload = returnData.payload;
-                        if (!_this._collisionsCallbackArray[returnPayload.collisionId])
-                            return;
-                        _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
-                        //cleanup
-                        _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
-                        break;
-                }
-            };
-            this._collisionsCallbackArray = [];
-            this._init = false;
-            this._runningUpdated = 0;
-            this._runningCollisionTask = false;
-            this._addUpdateMeshesList = {};
-            this._addUpdateGeometriesList = {};
-            this._toRemoveGeometryArray = [];
-            this._toRemoveMeshesArray = [];
-        }
-        CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
-            if (!this._init)
-                return;
-            if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
-                return;
-            position.divideToRef(collider.radius, this._scaledPosition);
-            velocity.divideToRef(collider.radius, this._scaledVelocity);
-            this._collisionsCallbackArray[collisionIndex] = onNewPosition;
-            var payload = {
-                collider: {
-                    position: this._scaledPosition.asArray(),
-                    velocity: this._scaledVelocity.asArray(),
-                    radius: collider.radius.asArray()
-                },
-                collisionId: collisionIndex,
-                excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
-                maximumRetry: maximumRetry
-            };
-            var message = {
-                payload: payload,
-                taskType: WorkerTaskType.COLLIDE
-            };
-            this._worker.postMessage(message);
-        };
-        CollisionCoordinatorWorker.prototype.init = function (scene) {
-            this._scene = scene;
-            this._scene.registerAfterRender(this._afterRender);
-            var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
-            this._worker = new Worker(workerUrl);
-            this._worker.onmessage = this._onMessageFromWorker;
-            var message = {
-                payload: {},
-                taskType: WorkerTaskType.INIT
-            };
-            this._worker.postMessage(message);
-        };
-        CollisionCoordinatorWorker.prototype.destroy = function () {
-            this._scene.unregisterAfterRender(this._afterRender);
-            this._worker.terminate();
-        };
-        CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
-            mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
-            this.onMeshUpdated(mesh);
-        };
-        CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
-            this._toRemoveMeshesArray.push(mesh.uniqueId);
-        };
-        CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
-            //TODO this will break if the user uses his own function. This should be an array of callbacks!
-            geometry.onGeometryUpdated = this.onGeometryUpdated;
-            this.onGeometryUpdated(geometry);
-        };
-        CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
-            this._toRemoveGeometryArray.push(geometry.id);
-        };
-        CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
-            var submeshes = [];
-            if (mesh.subMeshes) {
-                submeshes = mesh.subMeshes.map(function (sm, idx) {
-                    return {
-                        position: idx,
-                        verticesStart: sm.verticesStart,
-                        verticesCount: sm.verticesCount,
-                        indexStart: sm.indexStart,
-                        indexCount: sm.indexCount,
-                        hasMaterial: !!sm.getMaterial(),
-                        sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
-                        sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
-                        boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
-                        boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
-                    };
-                });
-            }
-            var geometryId = null;
-            if (mesh instanceof BABYLON.Mesh) {
-                geometryId = mesh.geometry ? mesh.geometry.id : null;
-            }
-            else if (mesh instanceof BABYLON.InstancedMesh) {
-                geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
-            }
-            return {
-                uniqueId: mesh.uniqueId,
-                id: mesh.id,
-                name: mesh.name,
-                geometryId: geometryId,
-                sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
-                sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
-                boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
-                boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
-                worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
-                subMeshes: submeshes,
-                checkCollisions: mesh.checkCollisions
-            };
-        };
-        CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
-            return {
-                id: geometry.id,
-                positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
-                normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
-                indices: new Int32Array(geometry.getIndices() || []),
-            };
-        };
-        return CollisionCoordinatorWorker;
-    }());
-    BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
-    var CollisionCoordinatorLegacy = (function () {
-        function CollisionCoordinatorLegacy() {
-            this._scaledPosition = BABYLON.Vector3.Zero();
-            this._scaledVelocity = BABYLON.Vector3.Zero();
-            this._finalPosition = BABYLON.Vector3.Zero();
-        }
-        CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
-            position.divideToRef(collider.radius, this._scaledPosition);
-            velocity.divideToRef(collider.radius, this._scaledVelocity);
-            collider.collidedMesh = null;
-            collider.retry = 0;
-            collider.initialVelocity = this._scaledVelocity;
-            collider.initialPosition = this._scaledPosition;
-            this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
-            this._finalPosition.multiplyInPlace(collider.radius);
-            //run the callback
-            onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
-        };
-        CollisionCoordinatorLegacy.prototype.init = function (scene) {
-            this._scene = scene;
-        };
-        CollisionCoordinatorLegacy.prototype.destroy = function () {
-            //Legacy need no destruction method.
-        };
-        //No update in legacy mode
-        CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
-            if (excludedMesh === void 0) { excludedMesh = null; }
-            var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
-            if (collider.retry >= maximumRetry) {
-                finalPosition.copyFrom(position);
-                return;
-            }
-            collider._initialize(position, velocity, closeDistance);
-            // Check all meshes
-            for (var index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
-                    mesh._checkCollision(collider);
-                }
-            }
-            if (!collider.collisionFound) {
-                position.addToRef(velocity, finalPosition);
-                return;
-            }
-            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
-                collider._getResponse(position, velocity);
-            }
-            if (velocity.length() <= closeDistance) {
-                finalPosition.copyFrom(position);
-                return;
-            }
-            collider.retry++;
-            this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
-        };
-        return CollisionCoordinatorLegacy;
-    }());
-    BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.collisionCoordinator.js.map
+var BABYLON;
+(function (BABYLON) {
+    //WebWorker code will be inserted to this variable.
+    BABYLON.CollisionWorker = "";
+    (function (WorkerTaskType) {
+        WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
+        WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
+        WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
+    })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
+    var WorkerTaskType = BABYLON.WorkerTaskType;
+    (function (WorkerReplyType) {
+        WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
+        WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
+    })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
+    var WorkerReplyType = BABYLON.WorkerReplyType;
+    var CollisionCoordinatorWorker = (function () {
+        function CollisionCoordinatorWorker() {
+            var _this = this;
+            this._scaledPosition = BABYLON.Vector3.Zero();
+            this._scaledVelocity = BABYLON.Vector3.Zero();
+            this.onMeshUpdated = function (mesh) {
+                _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
+            };
+            this.onGeometryUpdated = function (geometry) {
+                _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
+            };
+            this._afterRender = function () {
+                if (!_this._init)
+                    return;
+                if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
+                    return;
+                }
+                //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
+                //TODO make sure update runs as fast as possible to be able to update 60 FPS.
+                if (_this._runningUpdated > 4) {
+                    return;
+                }
+                ++_this._runningUpdated;
+                var payload = {
+                    updatedMeshes: _this._addUpdateMeshesList,
+                    updatedGeometries: _this._addUpdateGeometriesList,
+                    removedGeometries: _this._toRemoveGeometryArray,
+                    removedMeshes: _this._toRemoveMeshesArray
+                };
+                var message = {
+                    payload: payload,
+                    taskType: WorkerTaskType.UPDATE
+                };
+                var serializable = [];
+                for (var id in payload.updatedGeometries) {
+                    if (payload.updatedGeometries.hasOwnProperty(id)) {
+                        //prepare transferables
+                        serializable.push(message.payload.updatedGeometries[id].indices.buffer);
+                        serializable.push(message.payload.updatedGeometries[id].normals.buffer);
+                        serializable.push(message.payload.updatedGeometries[id].positions.buffer);
+                    }
+                }
+                _this._worker.postMessage(message, serializable);
+                _this._addUpdateMeshesList = {};
+                _this._addUpdateGeometriesList = {};
+                _this._toRemoveGeometryArray = [];
+                _this._toRemoveMeshesArray = [];
+            };
+            this._onMessageFromWorker = function (e) {
+                var returnData = e.data;
+                if (returnData.error != WorkerReplyType.SUCCESS) {
+                    //TODO what errors can be returned from the worker?
+                    BABYLON.Tools.Warn("error returned from worker!");
+                    return;
+                }
+                switch (returnData.taskType) {
+                    case WorkerTaskType.INIT:
+                        _this._init = true;
+                        //Update the worked with ALL of the scene's current state
+                        _this._scene.meshes.forEach(function (mesh) {
+                            _this.onMeshAdded(mesh);
+                        });
+                        _this._scene.getGeometries().forEach(function (geometry) {
+                            _this.onGeometryAdded(geometry);
+                        });
+                        break;
+                    case WorkerTaskType.UPDATE:
+                        _this._runningUpdated--;
+                        break;
+                    case WorkerTaskType.COLLIDE:
+                        _this._runningCollisionTask = false;
+                        var returnPayload = returnData.payload;
+                        if (!_this._collisionsCallbackArray[returnPayload.collisionId])
+                            return;
+                        _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
+                        //cleanup
+                        _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
+                        break;
+                }
+            };
+            this._collisionsCallbackArray = [];
+            this._init = false;
+            this._runningUpdated = 0;
+            this._runningCollisionTask = false;
+            this._addUpdateMeshesList = {};
+            this._addUpdateGeometriesList = {};
+            this._toRemoveGeometryArray = [];
+            this._toRemoveMeshesArray = [];
+        }
+        CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
+            if (!this._init)
+                return;
+            if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
+                return;
+            position.divideToRef(collider.radius, this._scaledPosition);
+            velocity.divideToRef(collider.radius, this._scaledVelocity);
+            this._collisionsCallbackArray[collisionIndex] = onNewPosition;
+            var payload = {
+                collider: {
+                    position: this._scaledPosition.asArray(),
+                    velocity: this._scaledVelocity.asArray(),
+                    radius: collider.radius.asArray()
+                },
+                collisionId: collisionIndex,
+                excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
+                maximumRetry: maximumRetry
+            };
+            var message = {
+                payload: payload,
+                taskType: WorkerTaskType.COLLIDE
+            };
+            this._worker.postMessage(message);
+        };
+        CollisionCoordinatorWorker.prototype.init = function (scene) {
+            this._scene = scene;
+            this._scene.registerAfterRender(this._afterRender);
+            var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
+            this._worker = new Worker(workerUrl);
+            this._worker.onmessage = this._onMessageFromWorker;
+            var message = {
+                payload: {},
+                taskType: WorkerTaskType.INIT
+            };
+            this._worker.postMessage(message);
+        };
+        CollisionCoordinatorWorker.prototype.destroy = function () {
+            this._scene.unregisterAfterRender(this._afterRender);
+            this._worker.terminate();
+        };
+        CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
+            mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
+            this.onMeshUpdated(mesh);
+        };
+        CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
+            this._toRemoveMeshesArray.push(mesh.uniqueId);
+        };
+        CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
+            //TODO this will break if the user uses his own function. This should be an array of callbacks!
+            geometry.onGeometryUpdated = this.onGeometryUpdated;
+            this.onGeometryUpdated(geometry);
+        };
+        CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
+            this._toRemoveGeometryArray.push(geometry.id);
+        };
+        CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
+            var submeshes = [];
+            if (mesh.subMeshes) {
+                submeshes = mesh.subMeshes.map(function (sm, idx) {
+                    return {
+                        position: idx,
+                        verticesStart: sm.verticesStart,
+                        verticesCount: sm.verticesCount,
+                        indexStart: sm.indexStart,
+                        indexCount: sm.indexCount,
+                        hasMaterial: !!sm.getMaterial(),
+                        sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
+                        sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
+                        boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
+                        boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
+                    };
+                });
+            }
+            var geometryId = null;
+            if (mesh instanceof BABYLON.Mesh) {
+                geometryId = mesh.geometry ? mesh.geometry.id : null;
+            }
+            else if (mesh instanceof BABYLON.InstancedMesh) {
+                geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
+            }
+            return {
+                uniqueId: mesh.uniqueId,
+                id: mesh.id,
+                name: mesh.name,
+                geometryId: geometryId,
+                sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
+                sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
+                boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
+                boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
+                worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
+                subMeshes: submeshes,
+                checkCollisions: mesh.checkCollisions
+            };
+        };
+        CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
+            return {
+                id: geometry.id,
+                positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
+                normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
+                indices: new Int32Array(geometry.getIndices() || []),
+            };
+        };
+        return CollisionCoordinatorWorker;
+    })();
+    BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
+    var CollisionCoordinatorLegacy = (function () {
+        function CollisionCoordinatorLegacy() {
+            this._scaledPosition = BABYLON.Vector3.Zero();
+            this._scaledVelocity = BABYLON.Vector3.Zero();
+            this._finalPosition = BABYLON.Vector3.Zero();
+        }
+        CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
+            position.divideToRef(collider.radius, this._scaledPosition);
+            velocity.divideToRef(collider.radius, this._scaledVelocity);
+            collider.collidedMesh = null;
+            collider.retry = 0;
+            collider.initialVelocity = this._scaledVelocity;
+            collider.initialPosition = this._scaledPosition;
+            this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
+            this._finalPosition.multiplyInPlace(collider.radius);
+            //run the callback
+            onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
+        };
+        CollisionCoordinatorLegacy.prototype.init = function (scene) {
+            this._scene = scene;
+        };
+        CollisionCoordinatorLegacy.prototype.destroy = function () {
+            //Legacy need no destruction method.
+        };
+        //No update in legacy mode
+        CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
+            if (excludedMesh === void 0) { excludedMesh = null; }
+            var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
+            if (collider.retry >= maximumRetry) {
+                finalPosition.copyFrom(position);
+                return;
+            }
+            collider._initialize(position, velocity, closeDistance);
+            // Check all meshes
+            for (var index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
+                    mesh._checkCollision(collider);
+                }
+            }
+            if (!collider.collisionFound) {
+                position.addToRef(velocity, finalPosition);
+                return;
+            }
+            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
+                collider._getResponse(position, velocity);
+            }
+            if (velocity.length() <= closeDistance) {
+                finalPosition.copyFrom(position);
+                return;
+            }
+            collider.retry++;
+            this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
+        };
+        return CollisionCoordinatorLegacy;
+    })();
+    BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
+})(BABYLON || (BABYLON = {}));

+ 243 - 244
src/Collisions/babylon.collisionWorker.js

@@ -1,244 +1,243 @@
-var BABYLON;
-(function (BABYLON) {
-    //If this file is included in the main thread, this will be initialized.
-    BABYLON.WorkerIncluded = true;
-    var CollisionCache = (function () {
-        function CollisionCache() {
-            this._meshes = {};
-            this._geometries = {};
-        }
-        CollisionCache.prototype.getMeshes = function () {
-            return this._meshes;
-        };
-        CollisionCache.prototype.getGeometries = function () {
-            return this._geometries;
-        };
-        CollisionCache.prototype.getMesh = function (id) {
-            return this._meshes[id];
-        };
-        CollisionCache.prototype.addMesh = function (mesh) {
-            this._meshes[mesh.uniqueId] = mesh;
-        };
-        CollisionCache.prototype.removeMesh = function (uniqueId) {
-            delete this._meshes[uniqueId];
-        };
-        CollisionCache.prototype.getGeometry = function (id) {
-            return this._geometries[id];
-        };
-        CollisionCache.prototype.addGeometry = function (geometry) {
-            this._geometries[geometry.id] = geometry;
-        };
-        CollisionCache.prototype.removeGeometry = function (id) {
-            delete this._geometries[id];
-        };
-        return CollisionCache;
-    }());
-    BABYLON.CollisionCache = CollisionCache;
-    var CollideWorker = (function () {
-        function CollideWorker(collider, _collisionCache, finalPosition) {
-            this.collider = collider;
-            this._collisionCache = _collisionCache;
-            this.finalPosition = finalPosition;
-            this.collisionsScalingMatrix = BABYLON.Matrix.Zero();
-            this.collisionTranformationMatrix = BABYLON.Matrix.Zero();
-        }
-        CollideWorker.prototype.collideWithWorld = function (position, velocity, maximumRetry, excludedMeshUniqueId) {
-            //TODO CollisionsEpsilon should be defined here and not in the engine.
-            var closeDistance = 0.01; //is initializing here correct? A quick look - looks like it is fine.
-            if (this.collider.retry >= maximumRetry) {
-                this.finalPosition.copyFrom(position);
-                return;
-            }
-            this.collider._initialize(position, velocity, closeDistance);
-            // Check all meshes
-            var meshes = this._collisionCache.getMeshes();
-            var keys = Object.keys(meshes);
-            var len = keys.length;
-            var uniqueId;
-            for (var i = 0; i < len; ++i) {
-                uniqueId = keys[i];
-                if (parseInt(uniqueId) != excludedMeshUniqueId) {
-                    var mesh = meshes[uniqueId];
-                    if (mesh.checkCollisions)
-                        this.checkCollision(mesh);
-                }
-            }
-            if (!this.collider.collisionFound) {
-                position.addToRef(velocity, this.finalPosition);
-                return;
-            }
-            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
-                this.collider._getResponse(position, velocity);
-            }
-            if (velocity.length() <= closeDistance) {
-                this.finalPosition.copyFrom(position);
-                return;
-            }
-            this.collider.retry++;
-            this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
-        };
-        CollideWorker.prototype.checkCollision = function (mesh) {
-            if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
-                return;
-            }
-            ;
-            // Transformation matrix
-            BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
-            var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
-            worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
-            this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
-            //return colTransMat;
-        };
-        CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
-            //if (this._submeshesOctree && this.useOctreeForCollisions) {
-            //    var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
-            //    var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
-            //    len = intersections.length;
-            //    subMeshes = intersections.data;
-            //} else {
-            var subMeshes = mesh.subMeshes;
-            var len = subMeshes.length;
-            //}
-            if (!mesh.geometryId) {
-                console.log("no mesh geometry id");
-                return;
-            }
-            var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
-            if (!meshGeometry) {
-                console.log("couldn't find geometry", mesh.geometryId);
-                return;
-            }
-            for (var index = 0; index < len; index++) {
-                var subMesh = subMeshes[index];
-                // Bounding test
-                if (len > 1 && !this.checkSubmeshCollision(subMesh))
-                    continue;
-                this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
-                if (this.collider.collisionFound) {
-                    this.collider.collidedMesh = mesh.uniqueId;
-                }
-            }
-        };
-        CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
-            if (!meshGeometry['positionsArray']) {
-                meshGeometry['positionsArray'] = [];
-                for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
-                    var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
-                    meshGeometry['positionsArray'].push(p);
-                }
-            }
-            if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
-                subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
-                subMesh['_lastColliderWorldVertices'] = [];
-                subMesh['_trianglePlanes'] = [];
-                var start = subMesh.verticesStart;
-                var end = (subMesh.verticesStart + subMesh.verticesCount);
-                for (var i = start; i < end; i++) {
-                    subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(meshGeometry['positionsArray'][i], transformMatrix));
-                }
-            }
-            // Collide
-            this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
-        };
-        CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
-            return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
-        };
-        return CollideWorker;
-    }());
-    BABYLON.CollideWorker = CollideWorker;
-    var CollisionDetectorTransferable = (function () {
-        function CollisionDetectorTransferable() {
-        }
-        CollisionDetectorTransferable.prototype.onInit = function (payload) {
-            this._collisionCache = new CollisionCache();
-            var reply = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.INIT
-            };
-            postMessage(reply, undefined);
-        };
-        CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
-            var _this = this;
-            var replay = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.UPDATE
-            };
-            try {
-                for (var id in payload.updatedGeometries) {
-                    if (payload.updatedGeometries.hasOwnProperty(id)) {
-                        this._collisionCache.addGeometry(payload.updatedGeometries[id]);
-                    }
-                }
-                for (var uniqueId in payload.updatedMeshes) {
-                    if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
-                        this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
-                    }
-                }
-                payload.removedGeometries.forEach(function (id) {
-                    _this._collisionCache.removeGeometry(id);
-                });
-                payload.removedMeshes.forEach(function (uniqueId) {
-                    _this._collisionCache.removeMesh(uniqueId);
-                });
-            }
-            catch (x) {
-                replay.error = BABYLON.WorkerReplyType.UNKNOWN_ERROR;
-            }
-            postMessage(replay, undefined);
-        };
-        CollisionDetectorTransferable.prototype.onCollision = function (payload) {
-            var finalPosition = BABYLON.Vector3.Zero();
-            //create a new collider
-            var collider = new BABYLON.Collider();
-            collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
-            var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
-            colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
-            var replyPayload = {
-                collidedMeshUniqueId: collider.collidedMesh,
-                collisionId: payload.collisionId,
-                newPosition: finalPosition.asArray()
-            };
-            var reply = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.COLLIDE,
-                payload: replyPayload
-            };
-            postMessage(reply, undefined);
-        };
-        return CollisionDetectorTransferable;
-    }());
-    BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
-    //check if we are in a web worker, as this code should NOT run on the main UI thread
-    try {
-        if (self && self instanceof WorkerGlobalScope) {
-            //Window hack to allow including babylonjs native code. the <any> is for typescript.
-            window = {};
-            //scripts were not included, standalone worker
-            if (!BABYLON.Collider) {
-                importScripts("./babylon.collisionCoordinator.js");
-                importScripts("./babylon.collider.js");
-                importScripts("../Math/babylon.math.js");
-            }
-            var collisionDetector = new CollisionDetectorTransferable();
-            var onNewMessage = function (event) {
-                var message = event.data;
-                switch (message.taskType) {
-                    case BABYLON.WorkerTaskType.INIT:
-                        collisionDetector.onInit(message.payload);
-                        break;
-                    case BABYLON.WorkerTaskType.COLLIDE:
-                        collisionDetector.onCollision(message.payload);
-                        break;
-                    case BABYLON.WorkerTaskType.UPDATE:
-                        collisionDetector.onUpdate(message.payload);
-                        break;
-                }
-            };
-            self.onmessage = onNewMessage;
-        }
-    }
-    catch (e) {
-        console.log("single worker init");
-    }
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.collisionWorker.js.map
+var BABYLON;
+(function (BABYLON) {
+    //If this file is included in the main thread, this will be initialized.
+    BABYLON.WorkerIncluded = true;
+    var CollisionCache = (function () {
+        function CollisionCache() {
+            this._meshes = {};
+            this._geometries = {};
+        }
+        CollisionCache.prototype.getMeshes = function () {
+            return this._meshes;
+        };
+        CollisionCache.prototype.getGeometries = function () {
+            return this._geometries;
+        };
+        CollisionCache.prototype.getMesh = function (id) {
+            return this._meshes[id];
+        };
+        CollisionCache.prototype.addMesh = function (mesh) {
+            this._meshes[mesh.uniqueId] = mesh;
+        };
+        CollisionCache.prototype.removeMesh = function (uniqueId) {
+            delete this._meshes[uniqueId];
+        };
+        CollisionCache.prototype.getGeometry = function (id) {
+            return this._geometries[id];
+        };
+        CollisionCache.prototype.addGeometry = function (geometry) {
+            this._geometries[geometry.id] = geometry;
+        };
+        CollisionCache.prototype.removeGeometry = function (id) {
+            delete this._geometries[id];
+        };
+        return CollisionCache;
+    })();
+    BABYLON.CollisionCache = CollisionCache;
+    var CollideWorker = (function () {
+        function CollideWorker(collider, _collisionCache, finalPosition) {
+            this.collider = collider;
+            this._collisionCache = _collisionCache;
+            this.finalPosition = finalPosition;
+            this.collisionsScalingMatrix = BABYLON.Matrix.Zero();
+            this.collisionTranformationMatrix = BABYLON.Matrix.Zero();
+        }
+        CollideWorker.prototype.collideWithWorld = function (position, velocity, maximumRetry, excludedMeshUniqueId) {
+            //TODO CollisionsEpsilon should be defined here and not in the engine.
+            var closeDistance = 0.01; //is initializing here correct? A quick look - looks like it is fine.
+            if (this.collider.retry >= maximumRetry) {
+                this.finalPosition.copyFrom(position);
+                return;
+            }
+            this.collider._initialize(position, velocity, closeDistance);
+            // Check all meshes
+            var meshes = this._collisionCache.getMeshes();
+            var keys = Object.keys(meshes);
+            var len = keys.length;
+            var uniqueId;
+            for (var i = 0; i < len; ++i) {
+                uniqueId = keys[i];
+                if (parseInt(uniqueId) != excludedMeshUniqueId) {
+                    var mesh = meshes[uniqueId];
+                    if (mesh.checkCollisions)
+                        this.checkCollision(mesh);
+                }
+            }
+            if (!this.collider.collisionFound) {
+                position.addToRef(velocity, this.finalPosition);
+                return;
+            }
+            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
+                this.collider._getResponse(position, velocity);
+            }
+            if (velocity.length() <= closeDistance) {
+                this.finalPosition.copyFrom(position);
+                return;
+            }
+            this.collider.retry++;
+            this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
+        };
+        CollideWorker.prototype.checkCollision = function (mesh) {
+            if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
+                return;
+            }
+            ;
+            // Transformation matrix
+            BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
+            var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
+            worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
+            this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
+            //return colTransMat;
+        };
+        CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
+            //if (this._submeshesOctree && this.useOctreeForCollisions) {
+            //    var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
+            //    var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
+            //    len = intersections.length;
+            //    subMeshes = intersections.data;
+            //} else {
+            var subMeshes = mesh.subMeshes;
+            var len = subMeshes.length;
+            //}
+            if (!mesh.geometryId) {
+                console.log("no mesh geometry id");
+                return;
+            }
+            var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
+            if (!meshGeometry) {
+                console.log("couldn't find geometry", mesh.geometryId);
+                return;
+            }
+            for (var index = 0; index < len; index++) {
+                var subMesh = subMeshes[index];
+                // Bounding test
+                if (len > 1 && !this.checkSubmeshCollision(subMesh))
+                    continue;
+                this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
+                if (this.collider.collisionFound) {
+                    this.collider.collidedMesh = mesh.uniqueId;
+                }
+            }
+        };
+        CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
+            if (!meshGeometry['positionsArray']) {
+                meshGeometry['positionsArray'] = [];
+                for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
+                    var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
+                    meshGeometry['positionsArray'].push(p);
+                }
+            }
+            if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
+                subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
+                subMesh['_lastColliderWorldVertices'] = [];
+                subMesh['_trianglePlanes'] = [];
+                var start = subMesh.verticesStart;
+                var end = (subMesh.verticesStart + subMesh.verticesCount);
+                for (var i = start; i < end; i++) {
+                    subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(meshGeometry['positionsArray'][i], transformMatrix));
+                }
+            }
+            // Collide
+            this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
+        };
+        CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
+            return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
+        };
+        return CollideWorker;
+    })();
+    BABYLON.CollideWorker = CollideWorker;
+    var CollisionDetectorTransferable = (function () {
+        function CollisionDetectorTransferable() {
+        }
+        CollisionDetectorTransferable.prototype.onInit = function (payload) {
+            this._collisionCache = new CollisionCache();
+            var reply = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.INIT
+            };
+            postMessage(reply, undefined);
+        };
+        CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
+            var _this = this;
+            var replay = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.UPDATE
+            };
+            try {
+                for (var id in payload.updatedGeometries) {
+                    if (payload.updatedGeometries.hasOwnProperty(id)) {
+                        this._collisionCache.addGeometry(payload.updatedGeometries[id]);
+                    }
+                }
+                for (var uniqueId in payload.updatedMeshes) {
+                    if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
+                        this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
+                    }
+                }
+                payload.removedGeometries.forEach(function (id) {
+                    _this._collisionCache.removeGeometry(id);
+                });
+                payload.removedMeshes.forEach(function (uniqueId) {
+                    _this._collisionCache.removeMesh(uniqueId);
+                });
+            }
+            catch (x) {
+                replay.error = BABYLON.WorkerReplyType.UNKNOWN_ERROR;
+            }
+            postMessage(replay, undefined);
+        };
+        CollisionDetectorTransferable.prototype.onCollision = function (payload) {
+            var finalPosition = BABYLON.Vector3.Zero();
+            //create a new collider
+            var collider = new BABYLON.Collider();
+            collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
+            var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
+            colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
+            var replyPayload = {
+                collidedMeshUniqueId: collider.collidedMesh,
+                collisionId: payload.collisionId,
+                newPosition: finalPosition.asArray()
+            };
+            var reply = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.COLLIDE,
+                payload: replyPayload
+            };
+            postMessage(reply, undefined);
+        };
+        return CollisionDetectorTransferable;
+    })();
+    BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
+    //check if we are in a web worker, as this code should NOT run on the main UI thread
+    try {
+        if (self && self instanceof WorkerGlobalScope) {
+            //Window hack to allow including babylonjs native code. the <any> is for typescript.
+            window = {};
+            //scripts were not included, standalone worker
+            if (!BABYLON.Collider) {
+                importScripts("./babylon.collisionCoordinator.js");
+                importScripts("./babylon.collider.js");
+                importScripts("../Math/babylon.math.js");
+            }
+            var collisionDetector = new CollisionDetectorTransferable();
+            var onNewMessage = function (event) {
+                var message = event.data;
+                switch (message.taskType) {
+                    case BABYLON.WorkerTaskType.INIT:
+                        collisionDetector.onInit(message.payload);
+                        break;
+                    case BABYLON.WorkerTaskType.COLLIDE:
+                        collisionDetector.onCollision(message.payload);
+                        break;
+                    case BABYLON.WorkerTaskType.UPDATE:
+                        collisionDetector.onUpdate(message.payload);
+                        break;
+                }
+            };
+            self.onmessage = onNewMessage;
+        }
+    }
+    catch (e) {
+        console.log("single worker init");
+    }
+})(BABYLON || (BABYLON = {}));

+ 76 - 77
src/Collisions/babylon.pickingInfo.js

@@ -1,77 +1,76 @@
-var BABYLON;
-(function (BABYLON) {
-    var IntersectionInfo = (function () {
-        function IntersectionInfo(bu, bv, distance) {
-            this.bu = bu;
-            this.bv = bv;
-            this.distance = distance;
-            this.faceId = 0;
-            this.subMeshId = 0;
-        }
-        return IntersectionInfo;
-    }());
-    BABYLON.IntersectionInfo = IntersectionInfo;
-    var PickingInfo = (function () {
-        function PickingInfo() {
-            this.hit = false;
-            this.distance = 0;
-            this.pickedPoint = null;
-            this.pickedMesh = null;
-            this.bu = 0;
-            this.bv = 0;
-            this.faceId = -1;
-            this.subMeshId = 0;
-            this.pickedSprite = null;
-        }
-        // Methods
-        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
-            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
-            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
-            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
-                return null;
-            }
-            var indices = this.pickedMesh.getIndices();
-            var result;
-            if (useVerticesNormals) {
-                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
-                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
-                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
-                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
-                normal0 = normal0.scale(this.bu);
-                normal1 = normal1.scale(this.bv);
-                normal2 = normal2.scale(1.0 - this.bu - this.bv);
-                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
-            }
-            else {
-                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
-                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
-                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
-                var p1p2 = vertex1.subtract(vertex2);
-                var p3p2 = vertex3.subtract(vertex2);
-                result = BABYLON.Vector3.Cross(p1p2, p3p2);
-            }
-            if (useWorldCoordinates) {
-                result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
-            }
-            return BABYLON.Vector3.Normalize(result);
-        };
-        PickingInfo.prototype.getTextureCoordinates = function () {
-            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
-                return null;
-            }
-            var indices = this.pickedMesh.getIndices();
-            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
-            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
-            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
-            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
-            uv0 = uv0.scale(1.0 - this.bu - this.bv);
-            uv1 = uv1.scale(this.bu);
-            uv2 = uv2.scale(this.bv);
-            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
-        };
-        return PickingInfo;
-    }());
-    BABYLON.PickingInfo = PickingInfo;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.pickingInfo.js.map
+var BABYLON;
+(function (BABYLON) {
+    var IntersectionInfo = (function () {
+        function IntersectionInfo(bu, bv, distance) {
+            this.bu = bu;
+            this.bv = bv;
+            this.distance = distance;
+            this.faceId = 0;
+            this.subMeshId = 0;
+        }
+        return IntersectionInfo;
+    })();
+    BABYLON.IntersectionInfo = IntersectionInfo;
+    var PickingInfo = (function () {
+        function PickingInfo() {
+            this.hit = false;
+            this.distance = 0;
+            this.pickedPoint = null;
+            this.pickedMesh = null;
+            this.bu = 0;
+            this.bv = 0;
+            this.faceId = -1;
+            this.subMeshId = 0;
+            this.pickedSprite = null;
+        }
+        // Methods
+        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
+            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
+            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
+            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
+                return null;
+            }
+            var indices = this.pickedMesh.getIndices();
+            var result;
+            if (useVerticesNormals) {
+                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
+                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
+                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
+                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
+                normal0 = normal0.scale(this.bu);
+                normal1 = normal1.scale(this.bv);
+                normal2 = normal2.scale(1.0 - this.bu - this.bv);
+                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
+            }
+            else {
+                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
+                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
+                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
+                var p1p2 = vertex1.subtract(vertex2);
+                var p3p2 = vertex3.subtract(vertex2);
+                result = BABYLON.Vector3.Cross(p1p2, p3p2);
+            }
+            if (useWorldCoordinates) {
+                result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
+            }
+            return BABYLON.Vector3.Normalize(result);
+        };
+        PickingInfo.prototype.getTextureCoordinates = function () {
+            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                return null;
+            }
+            var indices = this.pickedMesh.getIndices();
+            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
+            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
+            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
+            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
+            uv0 = uv0.scale(1.0 - this.bu - this.bv);
+            uv1 = uv1.scale(this.bu);
+            uv2 = uv2.scale(this.bv);
+            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
+        };
+        return PickingInfo;
+    })();
+    BABYLON.PickingInfo = PickingInfo;
+})(BABYLON || (BABYLON = {}));

+ 88 - 89
src/Culling/Octrees/babylon.octree.js

@@ -1,89 +1,88 @@
-var BABYLON;
-(function (BABYLON) {
-    var Octree = (function () {
-        function Octree(creationFunc, maxBlockCapacity, maxDepth) {
-            if (maxDepth === void 0) { maxDepth = 2; }
-            this.maxDepth = maxDepth;
-            this.dynamicContent = new Array();
-            this._maxBlockCapacity = maxBlockCapacity || 64;
-            this._selectionContent = new BABYLON.SmartArray(1024);
-            this._creationFunc = creationFunc;
-        }
-        // Methods
-        Octree.prototype.update = function (worldMin, worldMax, entries) {
-            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
-        };
-        Octree.prototype.addMesh = function (entry) {
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.addEntry(entry);
-            }
-        };
-        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
-            }
-            if (allowDuplicate) {
-                this._selectionContent.concat(this.dynamicContent);
-            }
-            else {
-                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            }
-            return this._selectionContent;
-        };
-        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
-            }
-            if (allowDuplicate) {
-                this._selectionContent.concat(this.dynamicContent);
-            }
-            else {
-                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            }
-            return this._selectionContent;
-        };
-        Octree.prototype.intersectsRay = function (ray) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.intersectsRay(ray, this._selectionContent);
-            }
-            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            return this._selectionContent;
-        };
-        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
-            target.blocks = new Array();
-            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
-            // Segmenting space
-            for (var x = 0; x < 2; x++) {
-                for (var y = 0; y < 2; y++) {
-                    for (var z = 0; z < 2; z++) {
-                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
-                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
-                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
-                        block.addEntries(entries);
-                        target.blocks.push(block);
-                    }
-                }
-            }
-        };
-        Octree.CreationFuncForMeshes = function (entry, block) {
-            if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
-                block.entries.push(entry);
-            }
-        };
-        Octree.CreationFuncForSubMeshes = function (entry, block) {
-            if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
-                block.entries.push(entry);
-            }
-        };
-        return Octree;
-    }());
-    BABYLON.Octree = Octree;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.octree.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Octree = (function () {
+        function Octree(creationFunc, maxBlockCapacity, maxDepth) {
+            if (maxDepth === void 0) { maxDepth = 2; }
+            this.maxDepth = maxDepth;
+            this.dynamicContent = new Array();
+            this._maxBlockCapacity = maxBlockCapacity || 64;
+            this._selectionContent = new BABYLON.SmartArray(1024);
+            this._creationFunc = creationFunc;
+        }
+        // Methods
+        Octree.prototype.update = function (worldMin, worldMax, entries) {
+            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
+        };
+        Octree.prototype.addMesh = function (entry) {
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.addEntry(entry);
+            }
+        };
+        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
+            }
+            if (allowDuplicate) {
+                this._selectionContent.concat(this.dynamicContent);
+            }
+            else {
+                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            }
+            return this._selectionContent;
+        };
+        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
+            }
+            if (allowDuplicate) {
+                this._selectionContent.concat(this.dynamicContent);
+            }
+            else {
+                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            }
+            return this._selectionContent;
+        };
+        Octree.prototype.intersectsRay = function (ray) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.intersectsRay(ray, this._selectionContent);
+            }
+            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            return this._selectionContent;
+        };
+        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
+            target.blocks = new Array();
+            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
+            // Segmenting space
+            for (var x = 0; x < 2; x++) {
+                for (var y = 0; y < 2; y++) {
+                    for (var z = 0; z < 2; z++) {
+                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
+                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
+                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
+                        block.addEntries(entries);
+                        target.blocks.push(block);
+                    }
+                }
+            }
+        };
+        Octree.CreationFuncForMeshes = function (entry, block) {
+            if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
+                block.entries.push(entry);
+            }
+        };
+        Octree.CreationFuncForSubMeshes = function (entry, block) {
+            if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
+                block.entries.push(entry);
+            }
+        };
+        return Octree;
+    })();
+    BABYLON.Octree = Octree;
+})(BABYLON || (BABYLON = {}));

+ 122 - 123
src/Culling/Octrees/babylon.octreeBlock.js

@@ -1,123 +1,122 @@
-var BABYLON;
-(function (BABYLON) {
-    var OctreeBlock = (function () {
-        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
-            this.entries = new Array();
-            this._boundingVectors = new Array();
-            this._capacity = capacity;
-            this._depth = depth;
-            this._maxDepth = maxDepth;
-            this._creationFunc = creationFunc;
-            this._minPoint = minPoint;
-            this._maxPoint = maxPoint;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[2].x = maxPoint.x;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[3].y = maxPoint.y;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[4].z = maxPoint.z;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[5].z = minPoint.z;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[6].x = minPoint.x;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[7].y = minPoint.y;
-        }
-        Object.defineProperty(OctreeBlock.prototype, "capacity", {
-            // Property
-            get: function () {
-                return this._capacity;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
-            get: function () {
-                return this._minPoint;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
-            get: function () {
-                return this._maxPoint;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        OctreeBlock.prototype.addEntry = function (entry) {
-            if (this.blocks) {
-                for (var index = 0; index < this.blocks.length; index++) {
-                    var block = this.blocks[index];
-                    block.addEntry(entry);
-                }
-                return;
-            }
-            this._creationFunc(entry, this);
-            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
-                this.createInnerBlocks();
-            }
-        };
-        OctreeBlock.prototype.addEntries = function (entries) {
-            for (var index = 0; index < entries.length; index++) {
-                var mesh = entries[index];
-                this.addEntry(mesh);
-            }
-        };
-        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
-            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.select(frustumPlanes, selection, allowDuplicate);
-                    }
-                    return;
-                }
-                if (allowDuplicate) {
-                    selection.concat(this.entries);
-                }
-                else {
-                    selection.concatWithNoDuplicate(this.entries);
-                }
-            }
-        };
-        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
-            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
-                    }
-                    return;
-                }
-                if (allowDuplicate) {
-                    selection.concat(this.entries);
-                }
-                else {
-                    selection.concatWithNoDuplicate(this.entries);
-                }
-            }
-        };
-        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
-            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.intersectsRay(ray, selection);
-                    }
-                    return;
-                }
-                selection.concatWithNoDuplicate(this.entries);
-            }
-        };
-        OctreeBlock.prototype.createInnerBlocks = function () {
-            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
-        };
-        return OctreeBlock;
-    }());
-    BABYLON.OctreeBlock = OctreeBlock;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.octreeBlock.js.map
+var BABYLON;
+(function (BABYLON) {
+    var OctreeBlock = (function () {
+        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
+            this.entries = new Array();
+            this._boundingVectors = new Array();
+            this._capacity = capacity;
+            this._depth = depth;
+            this._maxDepth = maxDepth;
+            this._creationFunc = creationFunc;
+            this._minPoint = minPoint;
+            this._maxPoint = maxPoint;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[2].x = maxPoint.x;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[3].y = maxPoint.y;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[4].z = maxPoint.z;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[5].z = minPoint.z;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[6].x = minPoint.x;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[7].y = minPoint.y;
+        }
+        Object.defineProperty(OctreeBlock.prototype, "capacity", {
+            // Property
+            get: function () {
+                return this._capacity;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
+            get: function () {
+                return this._minPoint;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
+            get: function () {
+                return this._maxPoint;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        OctreeBlock.prototype.addEntry = function (entry) {
+            if (this.blocks) {
+                for (var index = 0; index < this.blocks.length; index++) {
+                    var block = this.blocks[index];
+                    block.addEntry(entry);
+                }
+                return;
+            }
+            this._creationFunc(entry, this);
+            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
+                this.createInnerBlocks();
+            }
+        };
+        OctreeBlock.prototype.addEntries = function (entries) {
+            for (var index = 0; index < entries.length; index++) {
+                var mesh = entries[index];
+                this.addEntry(mesh);
+            }
+        };
+        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
+            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.select(frustumPlanes, selection, allowDuplicate);
+                    }
+                    return;
+                }
+                if (allowDuplicate) {
+                    selection.concat(this.entries);
+                }
+                else {
+                    selection.concatWithNoDuplicate(this.entries);
+                }
+            }
+        };
+        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
+            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
+                    }
+                    return;
+                }
+                if (allowDuplicate) {
+                    selection.concat(this.entries);
+                }
+                else {
+                    selection.concatWithNoDuplicate(this.entries);
+                }
+            }
+        };
+        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
+            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.intersectsRay(ray, selection);
+                    }
+                    return;
+                }
+                selection.concatWithNoDuplicate(this.entries);
+            }
+        };
+        OctreeBlock.prototype.createInnerBlocks = function () {
+            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
+        };
+        return OctreeBlock;
+    })();
+    BABYLON.OctreeBlock = OctreeBlock;
+})(BABYLON || (BABYLON = {}));

+ 143 - 144
src/Culling/babylon.boundingBox.js

@@ -1,144 +1,143 @@
-var BABYLON;
-(function (BABYLON) {
-    var BoundingBox = (function () {
-        function BoundingBox(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this.vectors = new Array();
-            this.vectorsWorld = new Array();
-            // Bounding vectors
-            this.vectors.push(this.minimum.clone());
-            this.vectors.push(this.maximum.clone());
-            this.vectors.push(this.minimum.clone());
-            this.vectors[2].x = this.maximum.x;
-            this.vectors.push(this.minimum.clone());
-            this.vectors[3].y = this.maximum.y;
-            this.vectors.push(this.minimum.clone());
-            this.vectors[4].z = this.maximum.z;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[5].z = this.minimum.z;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[6].x = this.minimum.x;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[7].y = this.minimum.y;
-            // OBB
-            this.center = this.maximum.add(this.minimum).scale(0.5);
-            this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
-            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
-            // World
-            for (var index = 0; index < this.vectors.length; index++) {
-                this.vectorsWorld[index] = BABYLON.Vector3.Zero();
-            }
-            this.minimumWorld = BABYLON.Vector3.Zero();
-            this.maximumWorld = BABYLON.Vector3.Zero();
-            this._update(BABYLON.Matrix.Identity());
-        }
-        // Methods
-        BoundingBox.prototype.getWorldMatrix = function () {
-            return this._worldMatrix;
-        };
-        BoundingBox.prototype.setWorldMatrix = function (matrix) {
-            this._worldMatrix.copyFrom(matrix);
-            return this;
-        };
-        BoundingBox.prototype._update = function (world) {
-            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
-            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
-            for (var index = 0; index < this.vectors.length; index++) {
-                var v = this.vectorsWorld[index];
-                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
-                if (v.x < this.minimumWorld.x)
-                    this.minimumWorld.x = v.x;
-                if (v.y < this.minimumWorld.y)
-                    this.minimumWorld.y = v.y;
-                if (v.z < this.minimumWorld.z)
-                    this.minimumWorld.z = v.z;
-                if (v.x > this.maximumWorld.x)
-                    this.maximumWorld.x = v.x;
-                if (v.y > this.maximumWorld.y)
-                    this.maximumWorld.y = v.y;
-                if (v.z > this.maximumWorld.z)
-                    this.maximumWorld.z = v.z;
-            }
-            // OBB
-            this.maximumWorld.addToRef(this.minimumWorld, this.center);
-            this.center.scaleInPlace(0.5);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
-            this._worldMatrix = world;
-        };
-        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
-            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
-        };
-        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
-            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
-        };
-        BoundingBox.prototype.intersectsPoint = function (point) {
-            var delta = -BABYLON.Epsilon;
-            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
-                return false;
-            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
-                return false;
-            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
-                return false;
-            return true;
-        };
-        BoundingBox.prototype.intersectsSphere = function (sphere) {
-            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
-        };
-        BoundingBox.prototype.intersectsMinMax = function (min, max) {
-            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
-                return false;
-            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
-                return false;
-            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
-                return false;
-            return true;
-        };
-        // Statics
-        BoundingBox.Intersects = function (box0, box1) {
-            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
-                return false;
-            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
-                return false;
-            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
-                return false;
-            return true;
-        };
-        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
-            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
-            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
-            return (num <= (sphereRadius * sphereRadius));
-        };
-        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
-            for (var p = 0; p < 6; p++) {
-                for (var i = 0; i < 8; i++) {
-                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
-                        return false;
-                    }
-                }
-            }
-            return true;
-        };
-        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
-            for (var p = 0; p < 6; p++) {
-                var inCount = 8;
-                for (var i = 0; i < 8; i++) {
-                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
-                        --inCount;
-                    }
-                    else {
-                        break;
-                    }
-                }
-                if (inCount === 0)
-                    return false;
-            }
-            return true;
-        };
-        return BoundingBox;
-    }());
-    BABYLON.BoundingBox = BoundingBox;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.boundingBox.js.map
+var BABYLON;
+(function (BABYLON) {
+    var BoundingBox = (function () {
+        function BoundingBox(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this.vectors = new Array();
+            this.vectorsWorld = new Array();
+            // Bounding vectors
+            this.vectors.push(this.minimum.clone());
+            this.vectors.push(this.maximum.clone());
+            this.vectors.push(this.minimum.clone());
+            this.vectors[2].x = this.maximum.x;
+            this.vectors.push(this.minimum.clone());
+            this.vectors[3].y = this.maximum.y;
+            this.vectors.push(this.minimum.clone());
+            this.vectors[4].z = this.maximum.z;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[5].z = this.minimum.z;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[6].x = this.minimum.x;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[7].y = this.minimum.y;
+            // OBB
+            this.center = this.maximum.add(this.minimum).scale(0.5);
+            this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
+            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
+            // World
+            for (var index = 0; index < this.vectors.length; index++) {
+                this.vectorsWorld[index] = BABYLON.Vector3.Zero();
+            }
+            this.minimumWorld = BABYLON.Vector3.Zero();
+            this.maximumWorld = BABYLON.Vector3.Zero();
+            this._update(BABYLON.Matrix.Identity());
+        }
+        // Methods
+        BoundingBox.prototype.getWorldMatrix = function () {
+            return this._worldMatrix;
+        };
+        BoundingBox.prototype.setWorldMatrix = function (matrix) {
+            this._worldMatrix.copyFrom(matrix);
+            return this;
+        };
+        BoundingBox.prototype._update = function (world) {
+            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
+            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
+            for (var index = 0; index < this.vectors.length; index++) {
+                var v = this.vectorsWorld[index];
+                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
+                if (v.x < this.minimumWorld.x)
+                    this.minimumWorld.x = v.x;
+                if (v.y < this.minimumWorld.y)
+                    this.minimumWorld.y = v.y;
+                if (v.z < this.minimumWorld.z)
+                    this.minimumWorld.z = v.z;
+                if (v.x > this.maximumWorld.x)
+                    this.maximumWorld.x = v.x;
+                if (v.y > this.maximumWorld.y)
+                    this.maximumWorld.y = v.y;
+                if (v.z > this.maximumWorld.z)
+                    this.maximumWorld.z = v.z;
+            }
+            // OBB
+            this.maximumWorld.addToRef(this.minimumWorld, this.center);
+            this.center.scaleInPlace(0.5);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
+            this._worldMatrix = world;
+        };
+        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
+            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
+        };
+        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
+            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
+        };
+        BoundingBox.prototype.intersectsPoint = function (point) {
+            var delta = -BABYLON.Epsilon;
+            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
+                return false;
+            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
+                return false;
+            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
+                return false;
+            return true;
+        };
+        BoundingBox.prototype.intersectsSphere = function (sphere) {
+            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
+        };
+        BoundingBox.prototype.intersectsMinMax = function (min, max) {
+            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
+                return false;
+            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
+                return false;
+            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
+                return false;
+            return true;
+        };
+        // Statics
+        BoundingBox.Intersects = function (box0, box1) {
+            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
+                return false;
+            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
+                return false;
+            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
+                return false;
+            return true;
+        };
+        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
+            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
+            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
+            return (num <= (sphereRadius * sphereRadius));
+        };
+        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
+            for (var p = 0; p < 6; p++) {
+                for (var i = 0; i < 8; i++) {
+                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        };
+        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
+            for (var p = 0; p < 6; p++) {
+                var inCount = 8;
+                for (var i = 0; i < 8; i++) {
+                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
+                        --inCount;
+                    }
+                    else {
+                        break;
+                    }
+                }
+                if (inCount === 0)
+                    return false;
+            }
+            return true;
+        };
+        return BoundingBox;
+    })();
+    BABYLON.BoundingBox = BoundingBox;
+})(BABYLON || (BABYLON = {}));

+ 119 - 120
src/Culling/babylon.boundingInfo.js

@@ -1,120 +1,119 @@
-var BABYLON;
-(function (BABYLON) {
-    var computeBoxExtents = function (axis, box) {
-        var p = BABYLON.Vector3.Dot(box.center, axis);
-        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
-        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
-        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
-        var r = r0 + r1 + r2;
-        return {
-            min: p - r,
-            max: p + r
-        };
-    };
-    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
-    var axisOverlap = function (axis, box0, box1) {
-        var result0 = computeBoxExtents(axis, box0);
-        var result1 = computeBoxExtents(axis, box1);
-        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
-    };
-    var BoundingInfo = (function () {
-        function BoundingInfo(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this._isLocked = false;
-            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
-            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
-        }
-        Object.defineProperty(BoundingInfo.prototype, "isLocked", {
-            get: function () {
-                return this._isLocked;
-            },
-            set: function (value) {
-                this._isLocked = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        BoundingInfo.prototype.update = function (world) {
-            if (this._isLocked) {
-                return;
-            }
-            this.boundingBox._update(world);
-            this.boundingSphere._update(world);
-        };
-        BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
-            if (!this.boundingSphere.isInFrustum(frustumPlanes))
-                return false;
-            return this.boundingBox.isInFrustum(frustumPlanes);
-        };
-        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
-            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
-        };
-        BoundingInfo.prototype._checkCollision = function (collider) {
-            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
-        };
-        BoundingInfo.prototype.intersectsPoint = function (point) {
-            if (!this.boundingSphere.centerWorld) {
-                return false;
-            }
-            if (!this.boundingSphere.intersectsPoint(point)) {
-                return false;
-            }
-            if (!this.boundingBox.intersectsPoint(point)) {
-                return false;
-            }
-            return true;
-        };
-        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
-            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
-                return false;
-            }
-            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
-                return false;
-            }
-            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
-                return false;
-            }
-            if (!precise) {
-                return true;
-            }
-            var box0 = this.boundingBox;
-            var box1 = boundingInfo.boundingBox;
-            if (!axisOverlap(box0.directions[0], box0, box1))
-                return false;
-            if (!axisOverlap(box0.directions[1], box0, box1))
-                return false;
-            if (!axisOverlap(box0.directions[2], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[0], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[1], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[2], box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
-                return false;
-            return true;
-        };
-        return BoundingInfo;
-    }());
-    BABYLON.BoundingInfo = BoundingInfo;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.boundingInfo.js.map
+var BABYLON;
+(function (BABYLON) {
+    var computeBoxExtents = function (axis, box) {
+        var p = BABYLON.Vector3.Dot(box.center, axis);
+        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
+        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
+        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
+        var r = r0 + r1 + r2;
+        return {
+            min: p - r,
+            max: p + r
+        };
+    };
+    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
+    var axisOverlap = function (axis, box0, box1) {
+        var result0 = computeBoxExtents(axis, box0);
+        var result1 = computeBoxExtents(axis, box1);
+        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
+    };
+    var BoundingInfo = (function () {
+        function BoundingInfo(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this._isLocked = false;
+            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
+            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
+        }
+        Object.defineProperty(BoundingInfo.prototype, "isLocked", {
+            get: function () {
+                return this._isLocked;
+            },
+            set: function (value) {
+                this._isLocked = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        BoundingInfo.prototype.update = function (world) {
+            if (this._isLocked) {
+                return;
+            }
+            this.boundingBox._update(world);
+            this.boundingSphere._update(world);
+        };
+        BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
+            if (!this.boundingSphere.isInFrustum(frustumPlanes))
+                return false;
+            return this.boundingBox.isInFrustum(frustumPlanes);
+        };
+        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
+            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
+        };
+        BoundingInfo.prototype._checkCollision = function (collider) {
+            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
+        };
+        BoundingInfo.prototype.intersectsPoint = function (point) {
+            if (!this.boundingSphere.centerWorld) {
+                return false;
+            }
+            if (!this.boundingSphere.intersectsPoint(point)) {
+                return false;
+            }
+            if (!this.boundingBox.intersectsPoint(point)) {
+                return false;
+            }
+            return true;
+        };
+        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
+            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
+                return false;
+            }
+            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
+                return false;
+            }
+            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
+                return false;
+            }
+            if (!precise) {
+                return true;
+            }
+            var box0 = this.boundingBox;
+            var box1 = boundingInfo.boundingBox;
+            if (!axisOverlap(box0.directions[0], box0, box1))
+                return false;
+            if (!axisOverlap(box0.directions[1], box0, box1))
+                return false;
+            if (!axisOverlap(box0.directions[2], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[0], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[1], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[2], box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
+                return false;
+            return true;
+        };
+        return BoundingInfo;
+    })();
+    BABYLON.BoundingInfo = BoundingInfo;
+})(BABYLON || (BABYLON = {}));

+ 49 - 50
src/Culling/babylon.boundingSphere.js

@@ -1,50 +1,49 @@
-var BABYLON;
-(function (BABYLON) {
-    var BoundingSphere = (function () {
-        function BoundingSphere(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this._tempRadiusVector = BABYLON.Vector3.Zero();
-            var distance = BABYLON.Vector3.Distance(minimum, maximum);
-            this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
-            this.radius = distance * 0.5;
-            this.centerWorld = BABYLON.Vector3.Zero();
-            this._update(BABYLON.Matrix.Identity());
-        }
-        // Methods
-        BoundingSphere.prototype._update = function (world) {
-            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
-            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
-            this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
-        };
-        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
-            for (var i = 0; i < 6; i++) {
-                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
-                    return false;
-            }
-            return true;
-        };
-        BoundingSphere.prototype.intersectsPoint = function (point) {
-            var x = this.centerWorld.x - point.x;
-            var y = this.centerWorld.y - point.y;
-            var z = this.centerWorld.z - point.z;
-            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
-            if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
-                return false;
-            return true;
-        };
-        // Statics
-        BoundingSphere.Intersects = function (sphere0, sphere1) {
-            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
-            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
-            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
-            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
-            if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
-                return false;
-            return true;
-        };
-        return BoundingSphere;
-    }());
-    BABYLON.BoundingSphere = BoundingSphere;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.boundingSphere.js.map
+var BABYLON;
+(function (BABYLON) {
+    var BoundingSphere = (function () {
+        function BoundingSphere(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this._tempRadiusVector = BABYLON.Vector3.Zero();
+            var distance = BABYLON.Vector3.Distance(minimum, maximum);
+            this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
+            this.radius = distance * 0.5;
+            this.centerWorld = BABYLON.Vector3.Zero();
+            this._update(BABYLON.Matrix.Identity());
+        }
+        // Methods
+        BoundingSphere.prototype._update = function (world) {
+            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
+            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
+            this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
+        };
+        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
+            for (var i = 0; i < 6; i++) {
+                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
+                    return false;
+            }
+            return true;
+        };
+        BoundingSphere.prototype.intersectsPoint = function (point) {
+            var x = this.centerWorld.x - point.x;
+            var y = this.centerWorld.y - point.y;
+            var z = this.centerWorld.z - point.z;
+            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
+            if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
+                return false;
+            return true;
+        };
+        // Statics
+        BoundingSphere.Intersects = function (sphere0, sphere1) {
+            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
+            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
+            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
+            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
+            if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
+                return false;
+            return true;
+        };
+        return BoundingSphere;
+    })();
+    BABYLON.BoundingSphere = BoundingSphere;
+})(BABYLON || (BABYLON = {}));

+ 274 - 275
src/Culling/babylon.ray.js

@@ -1,275 +1,274 @@
-var BABYLON;
-(function (BABYLON) {
-    var Ray = (function () {
-        function Ray(origin, direction, length) {
-            if (length === void 0) { length = Number.MAX_VALUE; }
-            this.origin = origin;
-            this.direction = direction;
-            this.length = length;
-        }
-        // Methods
-        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
-            var d = 0.0;
-            var maxValue = Number.MAX_VALUE;
-            var inv;
-            var min;
-            var max;
-            var temp;
-            if (Math.abs(this.direction.x) < 0.0000001) {
-                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.x;
-                min = (minimum.x - this.origin.x) * inv;
-                max = (maximum.x - this.origin.x) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            if (Math.abs(this.direction.y) < 0.0000001) {
-                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.y;
-                min = (minimum.y - this.origin.y) * inv;
-                max = (maximum.y - this.origin.y) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            if (Math.abs(this.direction.z) < 0.0000001) {
-                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.z;
-                min = (minimum.z - this.origin.z) * inv;
-                max = (maximum.z - this.origin.z) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        Ray.prototype.intersectsBox = function (box) {
-            return this.intersectsBoxMinMax(box.minimum, box.maximum);
-        };
-        Ray.prototype.intersectsSphere = function (sphere) {
-            var x = sphere.center.x - this.origin.x;
-            var y = sphere.center.y - this.origin.y;
-            var z = sphere.center.z - this.origin.z;
-            var pyth = (x * x) + (y * y) + (z * z);
-            var rr = sphere.radius * sphere.radius;
-            if (pyth <= rr) {
-                return true;
-            }
-            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
-            if (dot < 0.0) {
-                return false;
-            }
-            var temp = pyth - (dot * dot);
-            return temp <= rr;
-        };
-        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
-            if (!this._edge1) {
-                this._edge1 = BABYLON.Vector3.Zero();
-                this._edge2 = BABYLON.Vector3.Zero();
-                this._pvec = BABYLON.Vector3.Zero();
-                this._tvec = BABYLON.Vector3.Zero();
-                this._qvec = BABYLON.Vector3.Zero();
-            }
-            vertex1.subtractToRef(vertex0, this._edge1);
-            vertex2.subtractToRef(vertex0, this._edge2);
-            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
-            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
-            if (det === 0) {
-                return null;
-            }
-            var invdet = 1 / det;
-            this.origin.subtractToRef(vertex0, this._tvec);
-            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
-            if (bu < 0 || bu > 1.0) {
-                return null;
-            }
-            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
-            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
-            if (bv < 0 || bu + bv > 1.0) {
-                return null;
-            }
-            //check if the distance is longer than the predefined length.
-            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
-            if (distance > this.length) {
-                return null;
-            }
-            return new BABYLON.IntersectionInfo(bu, bv, distance);
-        };
-        Ray.prototype.intersectsPlane = function (plane) {
-            var distance;
-            var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
-            if (Math.abs(result1) < 9.99999997475243E-07) {
-                return null;
-            }
-            else {
-                var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
-                distance = (-plane.d - result2) / result1;
-                if (distance < 0.0) {
-                    if (distance < -9.99999997475243E-07) {
-                        return null;
-                    }
-                    else {
-                        return 0;
-                    }
-                }
-                return distance;
-            }
-        };
-        /**
-         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
-         * @param sega the first point of the segment to test the intersection against
-         * @param segb the second point of the segment to test the intersection against
-         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
-         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
-         */
-        Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
-            var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
-            var u = segb.subtract(sega);
-            var v = rsegb.subtract(this.origin);
-            var w = sega.subtract(this.origin);
-            var a = BABYLON.Vector3.Dot(u, u); // always >= 0
-            var b = BABYLON.Vector3.Dot(u, v);
-            var c = BABYLON.Vector3.Dot(v, v); // always >= 0
-            var d = BABYLON.Vector3.Dot(u, w);
-            var e = BABYLON.Vector3.Dot(v, w);
-            var D = a * c - b * b; // always >= 0
-            var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
-            var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
-            // compute the line parameters of the two closest points
-            if (D < Ray.smallnum) {
-                sN = 0.0; // force using point P0 on segment S1
-                sD = 1.0; // to prevent possible division by 0.0 later
-                tN = e;
-                tD = c;
-            }
-            else {
-                sN = (b * e - c * d);
-                tN = (a * e - b * d);
-                if (sN < 0.0) {
-                    sN = 0.0;
-                    tN = e;
-                    tD = c;
-                }
-                else if (sN > sD) {
-                    sN = sD;
-                    tN = e + b;
-                    tD = c;
-                }
-            }
-            if (tN < 0.0) {
-                tN = 0.0;
-                // recompute sc for this edge
-                if (-d < 0.0) {
-                    sN = 0.0;
-                }
-                else if (-d > a)
-                    sN = sD;
-                else {
-                    sN = -d;
-                    sD = a;
-                }
-            }
-            else if (tN > tD) {
-                tN = tD;
-                // recompute sc for this edge
-                if ((-d + b) < 0.0) {
-                    sN = 0;
-                }
-                else if ((-d + b) > a) {
-                    sN = sD;
-                }
-                else {
-                    sN = (-d + b);
-                    sD = a;
-                }
-            }
-            // finally do the division to get sc and tc
-            sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
-            tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
-            // get the difference of the two closest points
-            var qtc = v.multiplyByFloats(tc, tc, tc);
-            var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
-            var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
-            if (isIntersected) {
-                return qtc.length();
-            }
-            return -1;
-        };
-        // Statics
-        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
-            var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
-            var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
-            var direction = end.subtract(start);
-            direction.normalize();
-            return new Ray(start, direction);
-        };
-        /**
-        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
-        * transformed to the given world matrix.
-        * @param origin The origin point
-        * @param end The end point
-        * @param world a matrix to transform the ray to. Default is the identity matrix.
-        */
-        Ray.CreateNewFromTo = function (origin, end, world) {
-            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
-            var direction = end.subtract(origin);
-            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
-            direction.normalize();
-            return Ray.Transform(new Ray(origin, direction, length), world);
-        };
-        Ray.Transform = function (ray, matrix) {
-            var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
-            var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
-            newDirection.normalize();
-            return new Ray(newOrigin, newDirection, ray.length);
-        };
-        Ray.smallnum = 0.00000001;
-        Ray.rayl = 10e8;
-        return Ray;
-    }());
-    BABYLON.Ray = Ray;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.ray.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Ray = (function () {
+        function Ray(origin, direction, length) {
+            if (length === void 0) { length = Number.MAX_VALUE; }
+            this.origin = origin;
+            this.direction = direction;
+            this.length = length;
+        }
+        // Methods
+        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
+            var d = 0.0;
+            var maxValue = Number.MAX_VALUE;
+            var inv;
+            var min;
+            var max;
+            var temp;
+            if (Math.abs(this.direction.x) < 0.0000001) {
+                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.x;
+                min = (minimum.x - this.origin.x) * inv;
+                max = (maximum.x - this.origin.x) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            if (Math.abs(this.direction.y) < 0.0000001) {
+                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.y;
+                min = (minimum.y - this.origin.y) * inv;
+                max = (maximum.y - this.origin.y) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            if (Math.abs(this.direction.z) < 0.0000001) {
+                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.z;
+                min = (minimum.z - this.origin.z) * inv;
+                max = (maximum.z - this.origin.z) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        Ray.prototype.intersectsBox = function (box) {
+            return this.intersectsBoxMinMax(box.minimum, box.maximum);
+        };
+        Ray.prototype.intersectsSphere = function (sphere) {
+            var x = sphere.center.x - this.origin.x;
+            var y = sphere.center.y - this.origin.y;
+            var z = sphere.center.z - this.origin.z;
+            var pyth = (x * x) + (y * y) + (z * z);
+            var rr = sphere.radius * sphere.radius;
+            if (pyth <= rr) {
+                return true;
+            }
+            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
+            if (dot < 0.0) {
+                return false;
+            }
+            var temp = pyth - (dot * dot);
+            return temp <= rr;
+        };
+        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
+            if (!this._edge1) {
+                this._edge1 = BABYLON.Vector3.Zero();
+                this._edge2 = BABYLON.Vector3.Zero();
+                this._pvec = BABYLON.Vector3.Zero();
+                this._tvec = BABYLON.Vector3.Zero();
+                this._qvec = BABYLON.Vector3.Zero();
+            }
+            vertex1.subtractToRef(vertex0, this._edge1);
+            vertex2.subtractToRef(vertex0, this._edge2);
+            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
+            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
+            if (det === 0) {
+                return null;
+            }
+            var invdet = 1 / det;
+            this.origin.subtractToRef(vertex0, this._tvec);
+            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
+            if (bu < 0 || bu > 1.0) {
+                return null;
+            }
+            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
+            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
+            if (bv < 0 || bu + bv > 1.0) {
+                return null;
+            }
+            //check if the distance is longer than the predefined length.
+            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
+            if (distance > this.length) {
+                return null;
+            }
+            return new BABYLON.IntersectionInfo(bu, bv, distance);
+        };
+        Ray.prototype.intersectsPlane = function (plane) {
+            var distance;
+            var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
+            if (Math.abs(result1) < 9.99999997475243E-07) {
+                return null;
+            }
+            else {
+                var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
+                distance = (-plane.d - result2) / result1;
+                if (distance < 0.0) {
+                    if (distance < -9.99999997475243E-07) {
+                        return null;
+                    }
+                    else {
+                        return 0;
+                    }
+                }
+                return distance;
+            }
+        };
+        /**
+         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
+         * @param sega the first point of the segment to test the intersection against
+         * @param segb the second point of the segment to test the intersection against
+         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
+         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
+         */
+        Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
+            var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
+            var u = segb.subtract(sega);
+            var v = rsegb.subtract(this.origin);
+            var w = sega.subtract(this.origin);
+            var a = BABYLON.Vector3.Dot(u, u); // always >= 0
+            var b = BABYLON.Vector3.Dot(u, v);
+            var c = BABYLON.Vector3.Dot(v, v); // always >= 0
+            var d = BABYLON.Vector3.Dot(u, w);
+            var e = BABYLON.Vector3.Dot(v, w);
+            var D = a * c - b * b; // always >= 0
+            var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
+            var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
+            // compute the line parameters of the two closest points
+            if (D < Ray.smallnum) {
+                sN = 0.0; // force using point P0 on segment S1
+                sD = 1.0; // to prevent possible division by 0.0 later
+                tN = e;
+                tD = c;
+            }
+            else {
+                sN = (b * e - c * d);
+                tN = (a * e - b * d);
+                if (sN < 0.0) {
+                    sN = 0.0;
+                    tN = e;
+                    tD = c;
+                }
+                else if (sN > sD) {
+                    sN = sD;
+                    tN = e + b;
+                    tD = c;
+                }
+            }
+            if (tN < 0.0) {
+                tN = 0.0;
+                // recompute sc for this edge
+                if (-d < 0.0) {
+                    sN = 0.0;
+                }
+                else if (-d > a)
+                    sN = sD;
+                else {
+                    sN = -d;
+                    sD = a;
+                }
+            }
+            else if (tN > tD) {
+                tN = tD;
+                // recompute sc for this edge
+                if ((-d + b) < 0.0) {
+                    sN = 0;
+                }
+                else if ((-d + b) > a) {
+                    sN = sD;
+                }
+                else {
+                    sN = (-d + b);
+                    sD = a;
+                }
+            }
+            // finally do the division to get sc and tc
+            sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
+            tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
+            // get the difference of the two closest points
+            var qtc = v.multiplyByFloats(tc, tc, tc);
+            var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
+            var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
+            if (isIntersected) {
+                return qtc.length();
+            }
+            return -1;
+        };
+        // Statics
+        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
+            var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
+            var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
+            var direction = end.subtract(start);
+            direction.normalize();
+            return new Ray(start, direction);
+        };
+        /**
+        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
+        * transformed to the given world matrix.
+        * @param origin The origin point
+        * @param end The end point
+        * @param world a matrix to transform the ray to. Default is the identity matrix.
+        */
+        Ray.CreateNewFromTo = function (origin, end, world) {
+            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
+            var direction = end.subtract(origin);
+            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
+            direction.normalize();
+            return Ray.Transform(new Ray(origin, direction, length), world);
+        };
+        Ray.Transform = function (ray, matrix) {
+            var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
+            var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
+            newDirection.normalize();
+            return new Ray(newOrigin, newDirection, ray.length);
+        };
+        Ray.smallnum = 0.00000001;
+        Ray.rayl = 10e8;
+        return Ray;
+    })();
+    BABYLON.Ray = Ray;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 679 - 680
src/Debug/babylon.debugLayer.js


+ 137 - 138
src/Debug/babylon.skeletonViewer.js

@@ -1,138 +1,137 @@
-var BABYLON;
-(function (BABYLON) {
-    var Debug;
-    (function (Debug) {
-        /**
-        * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
-        */
-        var SkeletonViewer = (function () {
-            function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
-                if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
-                if (renderingGroupId === void 0) { renderingGroupId = 1; }
-                this.skeleton = skeleton;
-                this.mesh = mesh;
-                this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
-                this.renderingGroupId = renderingGroupId;
-                this.color = BABYLON.Color3.White();
-                this._debugLines = [];
-                this._isEnabled = false;
-                this._scene = scene;
-                this.update();
-                this._renderFunction = this.update.bind(this);
-            }
-            Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
-                get: function () {
-                    return this._isEnabled;
-                },
-                set: function (value) {
-                    if (this._isEnabled === value) {
-                        return;
-                    }
-                    this._isEnabled = value;
-                    if (value) {
-                        this._scene.registerBeforeRender(this._renderFunction);
-                    }
-                    else {
-                        this._scene.unregisterBeforeRender(this._renderFunction);
-                    }
-                },
-                enumerable: true,
-                configurable: true
-            });
-            SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
-                if (x === void 0) { x = 0; }
-                if (y === void 0) { y = 0; }
-                if (z === void 0) { z = 0; }
-                var tmat = BABYLON.Tmp.Matrix[0];
-                var parentBone = bone.getParent();
-                tmat.copyFrom(bone.getLocalMatrix());
-                if (x !== 0 || y !== 0 || z !== 0) {
-                    var tmat2 = BABYLON.Tmp.Matrix[1];
-                    BABYLON.Matrix.IdentityToRef(tmat2);
-                    tmat2.m[12] = x;
-                    tmat2.m[13] = y;
-                    tmat2.m[14] = z;
-                    tmat2.multiplyToRef(tmat, tmat);
-                }
-                if (parentBone) {
-                    tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
-                }
-                tmat.multiplyToRef(meshMat, tmat);
-                position.x = tmat.m[12];
-                position.y = tmat.m[13];
-                position.z = tmat.m[14];
-            };
-            SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
-                var len = bones.length;
-                for (var i = 0; i < len; i++) {
-                    var bone = bones[i];
-                    var points = this._debugLines[i];
-                    if (!points) {
-                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
-                        this._debugLines[i] = points;
-                    }
-                    this._getBonePosition(points[0], bone, meshMat);
-                    this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
-                }
-            };
-            SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
-                var len = bones.length;
-                var boneNum = 0;
-                for (var i = len - 1; i >= 0; i--) {
-                    var childBone = bones[i];
-                    var parentBone = childBone.getParent();
-                    if (!parentBone) {
-                        continue;
-                    }
-                    var points = this._debugLines[boneNum];
-                    if (!points) {
-                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
-                        this._debugLines[boneNum] = points;
-                    }
-                    this._getBonePosition(points[0], childBone, meshMat);
-                    this._getBonePosition(points[1], parentBone, meshMat);
-                    boneNum++;
-                }
-            };
-            SkeletonViewer.prototype.update = function () {
-                if (this.autoUpdateBonesMatrices) {
-                    this._updateBoneMatrix(this.skeleton.bones[0]);
-                }
-                if (this.skeleton.bones[0].length === undefined) {
-                    this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
-                }
-                else {
-                    this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
-                }
-                if (!this._debugMesh) {
-                    this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
-                    this._debugMesh.renderingGroupId = this.renderingGroupId;
-                }
-                else {
-                    BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
-                }
-                this._debugMesh.color = this.color;
-            };
-            SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
-                if (bone.getParent()) {
-                    bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
-                }
-                var children = bone.children;
-                var len = children.length;
-                for (var i = 0; i < len; i++) {
-                    this._updateBoneMatrix(children[i]);
-                }
-            };
-            SkeletonViewer.prototype.dispose = function () {
-                if (this._debugMesh) {
-                    this.isEnabled = false;
-                    this._debugMesh.dispose();
-                    this._debugMesh = null;
-                }
-            };
-            return SkeletonViewer;
-        }());
-        Debug.SkeletonViewer = SkeletonViewer;
-    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.skeletonViewer.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Debug;
+    (function (Debug) {
+        /**
+        * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
+        */
+        var SkeletonViewer = (function () {
+            function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
+                if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
+                if (renderingGroupId === void 0) { renderingGroupId = 1; }
+                this.skeleton = skeleton;
+                this.mesh = mesh;
+                this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
+                this.renderingGroupId = renderingGroupId;
+                this.color = BABYLON.Color3.White();
+                this._debugLines = [];
+                this._isEnabled = false;
+                this._scene = scene;
+                this.update();
+                this._renderFunction = this.update.bind(this);
+            }
+            Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
+                get: function () {
+                    return this._isEnabled;
+                },
+                set: function (value) {
+                    if (this._isEnabled === value) {
+                        return;
+                    }
+                    this._isEnabled = value;
+                    if (value) {
+                        this._scene.registerBeforeRender(this._renderFunction);
+                    }
+                    else {
+                        this._scene.unregisterBeforeRender(this._renderFunction);
+                    }
+                },
+                enumerable: true,
+                configurable: true
+            });
+            SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
+                if (x === void 0) { x = 0; }
+                if (y === void 0) { y = 0; }
+                if (z === void 0) { z = 0; }
+                var tmat = BABYLON.Tmp.Matrix[0];
+                var parentBone = bone.getParent();
+                tmat.copyFrom(bone.getLocalMatrix());
+                if (x !== 0 || y !== 0 || z !== 0) {
+                    var tmat2 = BABYLON.Tmp.Matrix[1];
+                    BABYLON.Matrix.IdentityToRef(tmat2);
+                    tmat2.m[12] = x;
+                    tmat2.m[13] = y;
+                    tmat2.m[14] = z;
+                    tmat2.multiplyToRef(tmat, tmat);
+                }
+                if (parentBone) {
+                    tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
+                }
+                tmat.multiplyToRef(meshMat, tmat);
+                position.x = tmat.m[12];
+                position.y = tmat.m[13];
+                position.z = tmat.m[14];
+            };
+            SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
+                var len = bones.length;
+                for (var i = 0; i < len; i++) {
+                    var bone = bones[i];
+                    var points = this._debugLines[i];
+                    if (!points) {
+                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
+                        this._debugLines[i] = points;
+                    }
+                    this._getBonePosition(points[0], bone, meshMat);
+                    this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
+                }
+            };
+            SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
+                var len = bones.length;
+                var boneNum = 0;
+                for (var i = len - 1; i >= 0; i--) {
+                    var childBone = bones[i];
+                    var parentBone = childBone.getParent();
+                    if (!parentBone) {
+                        continue;
+                    }
+                    var points = this._debugLines[boneNum];
+                    if (!points) {
+                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
+                        this._debugLines[boneNum] = points;
+                    }
+                    this._getBonePosition(points[0], childBone, meshMat);
+                    this._getBonePosition(points[1], parentBone, meshMat);
+                    boneNum++;
+                }
+            };
+            SkeletonViewer.prototype.update = function () {
+                if (this.autoUpdateBonesMatrices) {
+                    this._updateBoneMatrix(this.skeleton.bones[0]);
+                }
+                if (this.skeleton.bones[0].length === undefined) {
+                    this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
+                }
+                else {
+                    this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
+                }
+                if (!this._debugMesh) {
+                    this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
+                    this._debugMesh.renderingGroupId = this.renderingGroupId;
+                }
+                else {
+                    BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
+                }
+                this._debugMesh.color = this.color;
+            };
+            SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
+                if (bone.getParent()) {
+                    bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
+                }
+                var children = bone.children;
+                var len = children.length;
+                for (var i = 0; i < len; i++) {
+                    this._updateBoneMatrix(children[i]);
+                }
+            };
+            SkeletonViewer.prototype.dispose = function () {
+                if (this._debugMesh) {
+                    this.isEnabled = false;
+                    this._debugMesh.dispose();
+                    this._debugMesh = null;
+                }
+            };
+            return SkeletonViewer;
+        })();
+        Debug.SkeletonViewer = SkeletonViewer;
+    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
+})(BABYLON || (BABYLON = {}));

+ 140 - 141
src/Layer/babylon.layer.js

@@ -1,141 +1,140 @@
-var BABYLON;
-(function (BABYLON) {
-    var Layer = (function () {
-        function Layer(name, imgUrl, scene, isBackground, color) {
-            this.name = name;
-            this.scale = new BABYLON.Vector2(1, 1);
-            this.offset = new BABYLON.Vector2(0, 0);
-            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
-            this._vertexBuffers = {};
-            // Events
-            /**
-            * An event triggered when the layer is disposed.
-            * @type {BABYLON.Observable}
-            */
-            this.onDisposeObservable = new BABYLON.Observable();
-            /**
-            * An event triggered before rendering the scene
-            * @type {BABYLON.Observable}
-            */
-            this.onBeforeRenderObservable = new BABYLON.Observable();
-            /**
-            * An event triggered after rendering the scene
-            * @type {BABYLON.Observable}
-            */
-            this.onAfterRenderObservable = new BABYLON.Observable();
-            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
-            this.isBackground = isBackground === undefined ? true : isBackground;
-            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
-            this._scene = scene;
-            this._scene.layers.push(this);
-            var engine = scene.getEngine();
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
-            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = engine.createIndexBuffer(indices);
-            // Effects
-            this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
-            this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
-        }
-        Object.defineProperty(Layer.prototype, "onDispose", {
-            set: function (callback) {
-                if (this._onDisposeObserver) {
-                    this.onDisposeObservable.remove(this._onDisposeObserver);
-                }
-                this._onDisposeObserver = this.onDisposeObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Layer.prototype, "onBeforeRender", {
-            set: function (callback) {
-                if (this._onBeforeRenderObserver) {
-                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
-                }
-                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Layer.prototype, "onAfterRender", {
-            set: function (callback) {
-                if (this._onAfterRenderObserver) {
-                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
-                }
-                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Layer.prototype.render = function () {
-            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
-            // Check
-            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
-                return;
-            var engine = this._scene.getEngine();
-            this.onBeforeRenderObservable.notifyObservers(this);
-            // Render
-            engine.enableEffect(currentEffect);
-            engine.setState(false);
-            // Texture
-            currentEffect.setTexture("textureSampler", this.texture);
-            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
-            // Color
-            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
-            // Scale / offset
-            currentEffect.setVector2("offset", this.offset);
-            currentEffect.setVector2("scale", this.scale);
-            // VBOs
-            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
-            // Draw order
-            if (!this._alphaTestEffect) {
-                engine.setAlphaMode(this.alphaBlendingMode);
-                engine.draw(true, 0, 6);
-                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-            }
-            else {
-                engine.draw(true, 0, 6);
-            }
-            this.onAfterRenderObservable.notifyObservers(this);
-        };
-        Layer.prototype.dispose = function () {
-            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
-            if (vertexBuffer) {
-                vertexBuffer.dispose();
-                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
-            }
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-            if (this.texture) {
-                this.texture.dispose();
-                this.texture = null;
-            }
-            // Remove from scene
-            var index = this._scene.layers.indexOf(this);
-            this._scene.layers.splice(index, 1);
-            // Callback
-            this.onDisposeObservable.notifyObservers(this);
-            this.onDisposeObservable.clear();
-            this.onAfterRenderObservable.clear();
-            this.onBeforeRenderObservable.clear();
-        };
-        return Layer;
-    }());
-    BABYLON.Layer = Layer;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.layer.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Layer = (function () {
+        function Layer(name, imgUrl, scene, isBackground, color) {
+            this.name = name;
+            this.scale = new BABYLON.Vector2(1, 1);
+            this.offset = new BABYLON.Vector2(0, 0);
+            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
+            this._vertexBuffers = {};
+            // Events
+            /**
+            * An event triggered when the layer is disposed.
+            * @type {BABYLON.Observable}
+            */
+            this.onDisposeObservable = new BABYLON.Observable();
+            /**
+            * An event triggered before rendering the scene
+            * @type {BABYLON.Observable}
+            */
+            this.onBeforeRenderObservable = new BABYLON.Observable();
+            /**
+            * An event triggered after rendering the scene
+            * @type {BABYLON.Observable}
+            */
+            this.onAfterRenderObservable = new BABYLON.Observable();
+            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
+            this.isBackground = isBackground === undefined ? true : isBackground;
+            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
+            this._scene = scene;
+            this._scene.layers.push(this);
+            var engine = scene.getEngine();
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
+            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = engine.createIndexBuffer(indices);
+            // Effects
+            this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
+            this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
+        }
+        Object.defineProperty(Layer.prototype, "onDispose", {
+            set: function (callback) {
+                if (this._onDisposeObserver) {
+                    this.onDisposeObservable.remove(this._onDisposeObserver);
+                }
+                this._onDisposeObserver = this.onDisposeObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Layer.prototype, "onBeforeRender", {
+            set: function (callback) {
+                if (this._onBeforeRenderObserver) {
+                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
+                }
+                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Layer.prototype, "onAfterRender", {
+            set: function (callback) {
+                if (this._onAfterRenderObserver) {
+                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
+                }
+                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Layer.prototype.render = function () {
+            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
+            // Check
+            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
+                return;
+            var engine = this._scene.getEngine();
+            this.onBeforeRenderObservable.notifyObservers(this);
+            // Render
+            engine.enableEffect(currentEffect);
+            engine.setState(false);
+            // Texture
+            currentEffect.setTexture("textureSampler", this.texture);
+            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
+            // Color
+            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
+            // Scale / offset
+            currentEffect.setVector2("offset", this.offset);
+            currentEffect.setVector2("scale", this.scale);
+            // VBOs
+            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
+            // Draw order
+            if (!this._alphaTestEffect) {
+                engine.setAlphaMode(this.alphaBlendingMode);
+                engine.draw(true, 0, 6);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            }
+            else {
+                engine.draw(true, 0, 6);
+            }
+            this.onAfterRenderObservable.notifyObservers(this);
+        };
+        Layer.prototype.dispose = function () {
+            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
+            if (vertexBuffer) {
+                vertexBuffer.dispose();
+                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
+            }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+            if (this.texture) {
+                this.texture.dispose();
+                this.texture = null;
+            }
+            // Remove from scene
+            var index = this._scene.layers.indexOf(this);
+            this._scene.layers.splice(index, 1);
+            // Callback
+            this.onDisposeObservable.notifyObservers(this);
+            this.onDisposeObservable.clear();
+            this.onAfterRenderObservable.clear();
+            this.onBeforeRenderObservable.clear();
+        };
+        return Layer;
+    })();
+    BABYLON.Layer = Layer;
+})(BABYLON || (BABYLON = {}));

+ 23 - 24
src/LensFlare/babylon.lensFlare.js

@@ -1,24 +1,23 @@
-var BABYLON;
-(function (BABYLON) {
-    var LensFlare = (function () {
-        function LensFlare(size, position, color, imgUrl, system) {
-            this.size = size;
-            this.position = position;
-            this.dispose = function () {
-                if (this.texture) {
-                    this.texture.dispose();
-                }
-                // Remove from scene
-                var index = this._system.lensFlares.indexOf(this);
-                this._system.lensFlares.splice(index, 1);
-            };
-            this.color = color || new BABYLON.Color3(1, 1, 1);
-            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
-            this._system = system;
-            system.lensFlares.push(this);
-        }
-        return LensFlare;
-    }());
-    BABYLON.LensFlare = LensFlare;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.lensFlare.js.map
+var BABYLON;
+(function (BABYLON) {
+    var LensFlare = (function () {
+        function LensFlare(size, position, color, imgUrl, system) {
+            this.size = size;
+            this.position = position;
+            this.dispose = function () {
+                if (this.texture) {
+                    this.texture.dispose();
+                }
+                // Remove from scene
+                var index = this._system.lensFlares.indexOf(this);
+                this._system.lensFlares.splice(index, 1);
+            };
+            this.color = color || new BABYLON.Color3(1, 1, 1);
+            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
+            this._system = system;
+            system.lensFlares.push(this);
+        }
+        return LensFlare;
+    })();
+    BABYLON.LensFlare = LensFlare;
+})(BABYLON || (BABYLON = {}));

+ 214 - 215
src/LensFlare/babylon.lensFlareSystem.js

@@ -1,215 +1,214 @@
-var BABYLON;
-(function (BABYLON) {
-    var LensFlareSystem = (function () {
-        function LensFlareSystem(name, emitter, scene) {
-            this.name = name;
-            this.lensFlares = new Array();
-            this.borderLimit = 300;
-            this.layerMask = 0x0FFFFFFF;
-            this._vertexBuffers = {};
-            this._isEnabled = true;
-            this._scene = scene;
-            this._emitter = emitter;
-            this.id = name;
-            scene.lensFlareSystems.push(this);
-            this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
-            var engine = scene.getEngine();
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = engine.createIndexBuffer(indices);
-            // Effects
-            this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
-        }
-        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
-            get: function () {
-                return this._isEnabled;
-            },
-            set: function (value) {
-                this._isEnabled = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        LensFlareSystem.prototype.getScene = function () {
-            return this._scene;
-        };
-        LensFlareSystem.prototype.getEmitter = function () {
-            return this._emitter;
-        };
-        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
-            this._emitter = newEmitter;
-        };
-        LensFlareSystem.prototype.getEmitterPosition = function () {
-            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
-        };
-        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
-            var position = this.getEmitterPosition();
-            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
-            this._positionX = position.x;
-            this._positionY = position.y;
-            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
-            if (position.z > 0) {
-                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
-                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
-                        return true;
-                }
-            }
-            return false;
-        };
-        LensFlareSystem.prototype._isVisible = function () {
-            if (!this._isEnabled) {
-                return false;
-            }
-            var emitterPosition = this.getEmitterPosition();
-            var direction = emitterPosition.subtract(this._scene.activeCamera.position);
-            var distance = direction.length();
-            direction.normalize();
-            var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
-            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
-            return !pickInfo.hit || pickInfo.distance > distance;
-        };
-        LensFlareSystem.prototype.render = function () {
-            if (!this._effect.isReady())
-                return false;
-            var engine = this._scene.getEngine();
-            var viewport = this._scene.activeCamera.viewport;
-            var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
-            // Position
-            if (!this.computeEffectivePosition(globalViewport)) {
-                return false;
-            }
-            // Visibility
-            if (!this._isVisible()) {
-                return false;
-            }
-            // Intensity
-            var awayX;
-            var awayY;
-            if (this._positionX < this.borderLimit + globalViewport.x) {
-                awayX = this.borderLimit + globalViewport.x - this._positionX;
-            }
-            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
-                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
-            }
-            else {
-                awayX = 0;
-            }
-            if (this._positionY < this.borderLimit + globalViewport.y) {
-                awayY = this.borderLimit + globalViewport.y - this._positionY;
-            }
-            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
-                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
-            }
-            else {
-                awayY = 0;
-            }
-            var away = (awayX > awayY) ? awayX : awayY;
-            if (away > this.borderLimit) {
-                away = this.borderLimit;
-            }
-            var intensity = 1.0 - (away / this.borderLimit);
-            if (intensity < 0) {
-                return false;
-            }
-            if (intensity > 1.0) {
-                intensity = 1.0;
-            }
-            // Position
-            var centerX = globalViewport.x + globalViewport.width / 2;
-            var centerY = globalViewport.y + globalViewport.height / 2;
-            var distX = centerX - this._positionX;
-            var distY = centerY - this._positionY;
-            // Effects
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            engine.setDepthBuffer(false);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
-            // VBOs
-            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
-            // Flares
-            for (var index = 0; index < this.lensFlares.length; index++) {
-                var flare = this.lensFlares[index];
-                var x = centerX - (distX * flare.position);
-                var y = centerY - (distY * flare.position);
-                var cw = flare.size;
-                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
-                var cx = 2 * (x / globalViewport.width) - 1.0;
-                var cy = 1.0 - 2 * (y / globalViewport.height);
-                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
-                this._effect.setMatrix("viewportMatrix", viewportMatrix);
-                // Texture
-                this._effect.setTexture("textureSampler", flare.texture);
-                // Color
-                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
-                // Draw order
-                engine.draw(true, 0, 6);
-            }
-            engine.setDepthBuffer(true);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-            return true;
-        };
-        LensFlareSystem.prototype.dispose = function () {
-            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
-            if (vertexBuffer) {
-                vertexBuffer.dispose();
-                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
-            }
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-            while (this.lensFlares.length) {
-                this.lensFlares[0].dispose();
-            }
-            // Remove from scene
-            var index = this._scene.lensFlareSystems.indexOf(this);
-            this._scene.lensFlareSystems.splice(index, 1);
-        };
-        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
-            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
-            var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
-            var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
-            lensFlareSystem.id = parsedLensFlareSystem.id || name;
-            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
-            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
-                var parsedFlare = parsedLensFlareSystem.flares[index];
-                var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
-            }
-            return lensFlareSystem;
-        };
-        LensFlareSystem.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.id = this.id;
-            serializationObject.name = this.name;
-            serializationObject.emitterId = this.getEmitter().id;
-            serializationObject.borderLimit = this.borderLimit;
-            serializationObject.flares = [];
-            for (var index = 0; index < this.lensFlares.length; index++) {
-                var flare = this.lensFlares[index];
-                serializationObject.flares.push({
-                    size: flare.size,
-                    position: flare.position,
-                    color: flare.color.asArray(),
-                    textureName: BABYLON.Tools.GetFilename(flare.texture.name)
-                });
-            }
-            return serializationObject;
-        };
-        return LensFlareSystem;
-    }());
-    BABYLON.LensFlareSystem = LensFlareSystem;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.lensFlareSystem.js.map
+var BABYLON;
+(function (BABYLON) {
+    var LensFlareSystem = (function () {
+        function LensFlareSystem(name, emitter, scene) {
+            this.name = name;
+            this.lensFlares = new Array();
+            this.borderLimit = 300;
+            this.layerMask = 0x0FFFFFFF;
+            this._vertexBuffers = {};
+            this._isEnabled = true;
+            this._scene = scene;
+            this._emitter = emitter;
+            this.id = name;
+            scene.lensFlareSystems.push(this);
+            this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
+            var engine = scene.getEngine();
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = engine.createIndexBuffer(indices);
+            // Effects
+            this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
+        }
+        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
+            get: function () {
+                return this._isEnabled;
+            },
+            set: function (value) {
+                this._isEnabled = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        LensFlareSystem.prototype.getScene = function () {
+            return this._scene;
+        };
+        LensFlareSystem.prototype.getEmitter = function () {
+            return this._emitter;
+        };
+        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
+            this._emitter = newEmitter;
+        };
+        LensFlareSystem.prototype.getEmitterPosition = function () {
+            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
+        };
+        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
+            var position = this.getEmitterPosition();
+            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
+            this._positionX = position.x;
+            this._positionY = position.y;
+            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
+            if (position.z > 0) {
+                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
+                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
+                        return true;
+                }
+            }
+            return false;
+        };
+        LensFlareSystem.prototype._isVisible = function () {
+            if (!this._isEnabled) {
+                return false;
+            }
+            var emitterPosition = this.getEmitterPosition();
+            var direction = emitterPosition.subtract(this._scene.activeCamera.position);
+            var distance = direction.length();
+            direction.normalize();
+            var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
+            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
+            return !pickInfo.hit || pickInfo.distance > distance;
+        };
+        LensFlareSystem.prototype.render = function () {
+            if (!this._effect.isReady())
+                return false;
+            var engine = this._scene.getEngine();
+            var viewport = this._scene.activeCamera.viewport;
+            var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
+            // Position
+            if (!this.computeEffectivePosition(globalViewport)) {
+                return false;
+            }
+            // Visibility
+            if (!this._isVisible()) {
+                return false;
+            }
+            // Intensity
+            var awayX;
+            var awayY;
+            if (this._positionX < this.borderLimit + globalViewport.x) {
+                awayX = this.borderLimit + globalViewport.x - this._positionX;
+            }
+            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
+                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
+            }
+            else {
+                awayX = 0;
+            }
+            if (this._positionY < this.borderLimit + globalViewport.y) {
+                awayY = this.borderLimit + globalViewport.y - this._positionY;
+            }
+            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
+                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
+            }
+            else {
+                awayY = 0;
+            }
+            var away = (awayX > awayY) ? awayX : awayY;
+            if (away > this.borderLimit) {
+                away = this.borderLimit;
+            }
+            var intensity = 1.0 - (away / this.borderLimit);
+            if (intensity < 0) {
+                return false;
+            }
+            if (intensity > 1.0) {
+                intensity = 1.0;
+            }
+            // Position
+            var centerX = globalViewport.x + globalViewport.width / 2;
+            var centerY = globalViewport.y + globalViewport.height / 2;
+            var distX = centerX - this._positionX;
+            var distY = centerY - this._positionY;
+            // Effects
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            engine.setDepthBuffer(false);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
+            // VBOs
+            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
+            // Flares
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
+                var x = centerX - (distX * flare.position);
+                var y = centerY - (distY * flare.position);
+                var cw = flare.size;
+                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
+                var cx = 2 * (x / globalViewport.width) - 1.0;
+                var cy = 1.0 - 2 * (y / globalViewport.height);
+                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
+                this._effect.setMatrix("viewportMatrix", viewportMatrix);
+                // Texture
+                this._effect.setTexture("textureSampler", flare.texture);
+                // Color
+                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
+                // Draw order
+                engine.draw(true, 0, 6);
+            }
+            engine.setDepthBuffer(true);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            return true;
+        };
+        LensFlareSystem.prototype.dispose = function () {
+            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
+            if (vertexBuffer) {
+                vertexBuffer.dispose();
+                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
+            }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+            while (this.lensFlares.length) {
+                this.lensFlares[0].dispose();
+            }
+            // Remove from scene
+            var index = this._scene.lensFlareSystems.indexOf(this);
+            this._scene.lensFlareSystems.splice(index, 1);
+        };
+        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
+            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
+            var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
+            var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
+            lensFlareSystem.id = parsedLensFlareSystem.id || name;
+            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
+            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
+                var parsedFlare = parsedLensFlareSystem.flares[index];
+                var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
+            }
+            return lensFlareSystem;
+        };
+        LensFlareSystem.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.id = this.id;
+            serializationObject.name = this.name;
+            serializationObject.emitterId = this.getEmitter().id;
+            serializationObject.borderLimit = this.borderLimit;
+            serializationObject.flares = [];
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
+                serializationObject.flares.push({
+                    size: flare.size,
+                    position: flare.position,
+                    color: flare.color.asArray(),
+                    textureName: BABYLON.Tools.GetFilename(flare.texture.name)
+                });
+            }
+            return serializationObject;
+        };
+        return LensFlareSystem;
+    })();
+    BABYLON.LensFlareSystem = LensFlareSystem;
+})(BABYLON || (BABYLON = {}));

+ 407 - 408
src/Lights/Shadows/babylon.shadowGenerator.js

@@ -1,408 +1,407 @@
-var BABYLON;
-(function (BABYLON) {
-    var ShadowGenerator = (function () {
-        function ShadowGenerator(mapSize, light) {
-            var _this = this;
-            // Members
-            this._filter = ShadowGenerator.FILTER_NONE;
-            this.blurScale = 2;
-            this._blurBoxOffset = 0;
-            this._bias = 0.00005;
-            this._lightDirection = BABYLON.Vector3.Zero();
-            this.forceBackFacesOnly = false;
-            this._darkness = 0;
-            this._transparencyShadow = false;
-            this._viewMatrix = BABYLON.Matrix.Zero();
-            this._projectionMatrix = BABYLON.Matrix.Zero();
-            this._transformMatrix = BABYLON.Matrix.Zero();
-            this._worldViewProjection = BABYLON.Matrix.Zero();
-            this._currentFaceIndex = 0;
-            this._currentFaceIndexCache = 0;
-            this._light = light;
-            this._scene = light.getScene();
-            this._mapSize = mapSize;
-            light._shadowGenerator = this;
-            // Render target
-            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
-            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.anisotropicFilteringLevel = 1;
-            this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
-            this._shadowMap.renderParticles = false;
-            this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
-                _this._currentFaceIndex = faceIndex;
-            });
-            this._shadowMap.onAfterUnbindObservable.add(function () {
-                if (!_this.useBlurVarianceShadowMap) {
-                    return;
-                }
-                if (!_this._shadowMap2) {
-                    _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
-                    _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
-                    _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
-                    _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
-                        effect.setTexture("textureSampler", _this._shadowMap);
-                    });
-                    _this.blurBoxOffset = 1;
-                }
-                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
-            });
-            // Custom render function
-            var renderSubMesh = function (subMesh) {
-                var mesh = subMesh.getRenderingMesh();
-                var scene = _this._scene;
-                var engine = scene.getEngine();
-                // Culling
-                engine.setState(subMesh.getMaterial().backFaceCulling);
-                // Managing instances
-                var batch = mesh._getInstancesRenderList(subMesh._id);
-                if (batch.mustReturn) {
-                    return;
-                }
-                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
-                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
-                    engine.enableEffect(_this._effect);
-                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
-                    var material = subMesh.getMaterial();
-                    _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
-                    _this._effect.setVector3("lightPosition", _this.getLight().position);
-                    if (_this.getLight().needCube()) {
-                        _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
-                    }
-                    // Alpha test
-                    if (material && material.needAlphaTesting()) {
-                        var alphaTexture = material.getAlphaTestTexture();
-                        _this._effect.setTexture("diffuseSampler", alphaTexture);
-                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
-                    }
-                    // Bones
-                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-                    }
-                    if (_this.forceBackFacesOnly) {
-                        engine.setState(true, 0, false, true);
-                    }
-                    // Draw
-                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
-                    if (_this.forceBackFacesOnly) {
-                        engine.setState(true, 0, false, false);
-                    }
-                }
-                else {
-                    // Need to reset refresh rate of the shadowMap
-                    _this._shadowMap.resetRefreshCounter();
-                }
-            };
-            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
-                var index;
-                for (index = 0; index < opaqueSubMeshes.length; index++) {
-                    renderSubMesh(opaqueSubMeshes.data[index]);
-                }
-                for (index = 0; index < alphaTestSubMeshes.length; index++) {
-                    renderSubMesh(alphaTestSubMeshes.data[index]);
-                }
-                if (_this._transparencyShadow) {
-                    for (index = 0; index < transparentSubMeshes.length; index++) {
-                        renderSubMesh(transparentSubMeshes.data[index]);
-                    }
-                }
-            };
-            this._shadowMap.onClearObservable.add(function (engine) {
-                if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
-                    engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
-                }
-                else {
-                    engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
-                }
-            });
-        }
-        Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
-            // Static
-            get: function () {
-                return ShadowGenerator._FILTER_NONE;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
-            get: function () {
-                return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
-            get: function () {
-                return ShadowGenerator._FILTER_POISSONSAMPLING;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
-            get: function () {
-                return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "bias", {
-            get: function () {
-                return this._bias;
-            },
-            set: function (bias) {
-                this._bias = bias;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
-            get: function () {
-                return this._blurBoxOffset;
-            },
-            set: function (value) {
-                var _this = this;
-                if (this._blurBoxOffset === value) {
-                    return;
-                }
-                this._blurBoxOffset = value;
-                if (this._boxBlurPostprocess) {
-                    this._boxBlurPostprocess.dispose();
-                }
-                this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
-                this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
-                    effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
-                });
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "filter", {
-            get: function () {
-                return this._filter;
-            },
-            set: function (value) {
-                if (this._filter === value) {
-                    return;
-                }
-                this._filter = value;
-                if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
-                    this._shadowMap.anisotropicFilteringLevel = 16;
-                    this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
-                }
-                else {
-                    this._shadowMap.anisotropicFilteringLevel = 1;
-                    this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
-                }
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
-                    (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
-                        this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
-            var defines = [];
-            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
-                defines.push("#define VSM");
-            }
-            if (this.getLight().needCube()) {
-                defines.push("#define CUBEMAP");
-            }
-            var attribs = [BABYLON.VertexBuffer.PositionKind];
-            var mesh = subMesh.getMesh();
-            var material = subMesh.getMaterial();
-            // Alpha test
-            if (material && material.needAlphaTesting()) {
-                defines.push("#define ALPHATEST");
-                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
-                    attribs.push(BABYLON.VertexBuffer.UVKind);
-                    defines.push("#define UV1");
-                }
-                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
-                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
-                    defines.push("#define UV2");
-                }
-            }
-            // Bones
-            if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
-                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
-                if (mesh.numBoneInfluencers > 4) {
-                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
-                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
-                }
-                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
-                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
-            }
-            else {
-                defines.push("#define NUM_BONE_INFLUENCERS 0");
-            }
-            // Instances
-            if (useInstances) {
-                defines.push("#define INSTANCES");
-                attribs.push("world0");
-                attribs.push("world1");
-                attribs.push("world2");
-                attribs.push("world3");
-            }
-            // Get correct effect      
-            var join = defines.join("\n");
-            if (this._cachedDefines !== join) {
-                this._cachedDefines = join;
-                this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
-            }
-            return this._effect.isReady();
-        };
-        ShadowGenerator.prototype.getShadowMap = function () {
-            return this._shadowMap;
-        };
-        ShadowGenerator.prototype.getShadowMapForRendering = function () {
-            if (this._shadowMap2) {
-                return this._shadowMap2;
-            }
-            return this._shadowMap;
-        };
-        ShadowGenerator.prototype.getLight = function () {
-            return this._light;
-        };
-        // Methods
-        ShadowGenerator.prototype.getTransformMatrix = function () {
-            var scene = this._scene;
-            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
-                return this._transformMatrix;
-            }
-            this._currentRenderID = scene.getRenderId();
-            this._currentFaceIndexCache = this._currentFaceIndex;
-            var lightPosition = this._light.position;
-            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
-            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
-                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
-            }
-            if (this._light.computeTransformedPosition()) {
-                lightPosition = this._light.transformedPosition;
-            }
-            if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
-                this._cachedPosition = lightPosition.clone();
-                this._cachedDirection = this._lightDirection.clone();
-                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
-                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
-                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
-            }
-            return this._transformMatrix;
-        };
-        ShadowGenerator.prototype.getDarkness = function () {
-            return this._darkness;
-        };
-        ShadowGenerator.prototype.setDarkness = function (darkness) {
-            if (darkness >= 1.0)
-                this._darkness = 1.0;
-            else if (darkness <= 0.0)
-                this._darkness = 0.0;
-            else
-                this._darkness = darkness;
-        };
-        ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
-            this._transparencyShadow = hasShadow;
-        };
-        ShadowGenerator.prototype._packHalf = function (depth) {
-            var scale = depth * 255.0;
-            var fract = scale - Math.floor(scale);
-            return new BABYLON.Vector2(depth - fract / 255.0, fract);
-        };
-        ShadowGenerator.prototype.dispose = function () {
-            this._shadowMap.dispose();
-            if (this._shadowMap2) {
-                this._shadowMap2.dispose();
-            }
-            if (this._downSamplePostprocess) {
-                this._downSamplePostprocess.dispose();
-            }
-            if (this._boxBlurPostprocess) {
-                this._boxBlurPostprocess.dispose();
-            }
-        };
-        ShadowGenerator.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.lightId = this._light.id;
-            serializationObject.mapSize = this.getShadowMap().getRenderSize();
-            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
-            serializationObject.usePoissonSampling = this.usePoissonSampling;
-            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
-            serializationObject.renderList = [];
-            for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
-                var mesh = this.getShadowMap().renderList[meshIndex];
-                serializationObject.renderList.push(mesh.id);
-            }
-            return serializationObject;
-        };
-        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
-            //casting to point light, as light is missing the position attr and typescript complains.
-            var light = scene.getLightByID(parsedShadowGenerator.lightId);
-            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
-            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
-                var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
-                meshes.forEach(function (mesh) {
-                    shadowGenerator.getShadowMap().renderList.push(mesh);
-                });
-            }
-            if (parsedShadowGenerator.usePoissonSampling) {
-                shadowGenerator.usePoissonSampling = true;
-            }
-            else if (parsedShadowGenerator.useVarianceShadowMap) {
-                shadowGenerator.useVarianceShadowMap = true;
-            }
-            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
-                shadowGenerator.useBlurVarianceShadowMap = true;
-                if (parsedShadowGenerator.blurScale) {
-                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
-                }
-                if (parsedShadowGenerator.blurBoxOffset) {
-                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
-                }
-            }
-            if (parsedShadowGenerator.bias !== undefined) {
-                shadowGenerator.bias = parsedShadowGenerator.bias;
-            }
-            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
-            return shadowGenerator;
-        };
-        ShadowGenerator._FILTER_NONE = 0;
-        ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
-        ShadowGenerator._FILTER_POISSONSAMPLING = 2;
-        ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
-        return ShadowGenerator;
-    }());
-    BABYLON.ShadowGenerator = ShadowGenerator;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.shadowGenerator.js.map
+var BABYLON;
+(function (BABYLON) {
+    var ShadowGenerator = (function () {
+        function ShadowGenerator(mapSize, light) {
+            var _this = this;
+            // Members
+            this._filter = ShadowGenerator.FILTER_NONE;
+            this.blurScale = 2;
+            this._blurBoxOffset = 0;
+            this._bias = 0.00005;
+            this._lightDirection = BABYLON.Vector3.Zero();
+            this.forceBackFacesOnly = false;
+            this._darkness = 0;
+            this._transparencyShadow = false;
+            this._viewMatrix = BABYLON.Matrix.Zero();
+            this._projectionMatrix = BABYLON.Matrix.Zero();
+            this._transformMatrix = BABYLON.Matrix.Zero();
+            this._worldViewProjection = BABYLON.Matrix.Zero();
+            this._currentFaceIndex = 0;
+            this._currentFaceIndexCache = 0;
+            this._light = light;
+            this._scene = light.getScene();
+            this._mapSize = mapSize;
+            light._shadowGenerator = this;
+            // Render target
+            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
+            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.anisotropicFilteringLevel = 1;
+            this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
+            this._shadowMap.renderParticles = false;
+            this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
+                _this._currentFaceIndex = faceIndex;
+            });
+            this._shadowMap.onAfterUnbindObservable.add(function () {
+                if (!_this.useBlurVarianceShadowMap) {
+                    return;
+                }
+                if (!_this._shadowMap2) {
+                    _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
+                    _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
+                    _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
+                    _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
+                        effect.setTexture("textureSampler", _this._shadowMap);
+                    });
+                    _this.blurBoxOffset = 1;
+                }
+                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
+            });
+            // Custom render function
+            var renderSubMesh = function (subMesh) {
+                var mesh = subMesh.getRenderingMesh();
+                var scene = _this._scene;
+                var engine = scene.getEngine();
+                // Culling
+                engine.setState(subMesh.getMaterial().backFaceCulling);
+                // Managing instances
+                var batch = mesh._getInstancesRenderList(subMesh._id);
+                if (batch.mustReturn) {
+                    return;
+                }
+                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
+                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
+                    engine.enableEffect(_this._effect);
+                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
+                    var material = subMesh.getMaterial();
+                    _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
+                    _this._effect.setVector3("lightPosition", _this.getLight().position);
+                    if (_this.getLight().needCube()) {
+                        _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
+                    }
+                    // Alpha test
+                    if (material && material.needAlphaTesting()) {
+                        var alphaTexture = material.getAlphaTestTexture();
+                        _this._effect.setTexture("diffuseSampler", alphaTexture);
+                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
+                    }
+                    // Bones
+                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
+                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
+                    }
+                    if (_this.forceBackFacesOnly) {
+                        engine.setState(true, 0, false, true);
+                    }
+                    // Draw
+                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
+                    if (_this.forceBackFacesOnly) {
+                        engine.setState(true, 0, false, false);
+                    }
+                }
+                else {
+                    // Need to reset refresh rate of the shadowMap
+                    _this._shadowMap.resetRefreshCounter();
+                }
+            };
+            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
+                var index;
+                for (index = 0; index < opaqueSubMeshes.length; index++) {
+                    renderSubMesh(opaqueSubMeshes.data[index]);
+                }
+                for (index = 0; index < alphaTestSubMeshes.length; index++) {
+                    renderSubMesh(alphaTestSubMeshes.data[index]);
+                }
+                if (_this._transparencyShadow) {
+                    for (index = 0; index < transparentSubMeshes.length; index++) {
+                        renderSubMesh(transparentSubMeshes.data[index]);
+                    }
+                }
+            };
+            this._shadowMap.onClearObservable.add(function (engine) {
+                if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
+                    engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
+                }
+                else {
+                    engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
+                }
+            });
+        }
+        Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
+            // Static
+            get: function () {
+                return ShadowGenerator._FILTER_NONE;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
+            get: function () {
+                return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
+            get: function () {
+                return ShadowGenerator._FILTER_POISSONSAMPLING;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
+            get: function () {
+                return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "bias", {
+            get: function () {
+                return this._bias;
+            },
+            set: function (bias) {
+                this._bias = bias;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
+            get: function () {
+                return this._blurBoxOffset;
+            },
+            set: function (value) {
+                var _this = this;
+                if (this._blurBoxOffset === value) {
+                    return;
+                }
+                this._blurBoxOffset = value;
+                if (this._boxBlurPostprocess) {
+                    this._boxBlurPostprocess.dispose();
+                }
+                this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
+                this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
+                    effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
+                });
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "filter", {
+            get: function () {
+                return this._filter;
+            },
+            set: function (value) {
+                if (this._filter === value) {
+                    return;
+                }
+                this._filter = value;
+                if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
+                    this._shadowMap.anisotropicFilteringLevel = 16;
+                    this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
+                }
+                else {
+                    this._shadowMap.anisotropicFilteringLevel = 1;
+                    this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
+                }
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
+                    (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
+                        this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
+            var defines = [];
+            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
+                defines.push("#define VSM");
+            }
+            if (this.getLight().needCube()) {
+                defines.push("#define CUBEMAP");
+            }
+            var attribs = [BABYLON.VertexBuffer.PositionKind];
+            var mesh = subMesh.getMesh();
+            var material = subMesh.getMaterial();
+            // Alpha test
+            if (material && material.needAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                    attribs.push(BABYLON.VertexBuffer.UVKind);
+                    defines.push("#define UV1");
+                }
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
+                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
+                    defines.push("#define UV2");
+                }
+            }
+            // Bones
+            if (mesh.useBones && mesh.computeBonesUsingShaders) {
+                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                if (mesh.numBoneInfluencers > 4) {
+                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
+                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
+                }
+                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
+            }
+            else {
+                defines.push("#define NUM_BONE_INFLUENCERS 0");
+            }
+            // Instances
+            if (useInstances) {
+                defines.push("#define INSTANCES");
+                attribs.push("world0");
+                attribs.push("world1");
+                attribs.push("world2");
+                attribs.push("world3");
+            }
+            // Get correct effect      
+            var join = defines.join("\n");
+            if (this._cachedDefines !== join) {
+                this._cachedDefines = join;
+                this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
+            }
+            return this._effect.isReady();
+        };
+        ShadowGenerator.prototype.getShadowMap = function () {
+            return this._shadowMap;
+        };
+        ShadowGenerator.prototype.getShadowMapForRendering = function () {
+            if (this._shadowMap2) {
+                return this._shadowMap2;
+            }
+            return this._shadowMap;
+        };
+        ShadowGenerator.prototype.getLight = function () {
+            return this._light;
+        };
+        // Methods
+        ShadowGenerator.prototype.getTransformMatrix = function () {
+            var scene = this._scene;
+            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
+                return this._transformMatrix;
+            }
+            this._currentRenderID = scene.getRenderId();
+            this._currentFaceIndexCache = this._currentFaceIndex;
+            var lightPosition = this._light.position;
+            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
+            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
+                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
+            }
+            if (this._light.computeTransformedPosition()) {
+                lightPosition = this._light.transformedPosition;
+            }
+            if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
+                this._cachedPosition = lightPosition.clone();
+                this._cachedDirection = this._lightDirection.clone();
+                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
+                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
+                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+            }
+            return this._transformMatrix;
+        };
+        ShadowGenerator.prototype.getDarkness = function () {
+            return this._darkness;
+        };
+        ShadowGenerator.prototype.setDarkness = function (darkness) {
+            if (darkness >= 1.0)
+                this._darkness = 1.0;
+            else if (darkness <= 0.0)
+                this._darkness = 0.0;
+            else
+                this._darkness = darkness;
+        };
+        ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
+            this._transparencyShadow = hasShadow;
+        };
+        ShadowGenerator.prototype._packHalf = function (depth) {
+            var scale = depth * 255.0;
+            var fract = scale - Math.floor(scale);
+            return new BABYLON.Vector2(depth - fract / 255.0, fract);
+        };
+        ShadowGenerator.prototype.dispose = function () {
+            this._shadowMap.dispose();
+            if (this._shadowMap2) {
+                this._shadowMap2.dispose();
+            }
+            if (this._downSamplePostprocess) {
+                this._downSamplePostprocess.dispose();
+            }
+            if (this._boxBlurPostprocess) {
+                this._boxBlurPostprocess.dispose();
+            }
+        };
+        ShadowGenerator.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.lightId = this._light.id;
+            serializationObject.mapSize = this.getShadowMap().getRenderSize();
+            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
+            serializationObject.usePoissonSampling = this.usePoissonSampling;
+            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
+            serializationObject.renderList = [];
+            for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
+                var mesh = this.getShadowMap().renderList[meshIndex];
+                serializationObject.renderList.push(mesh.id);
+            }
+            return serializationObject;
+        };
+        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
+            //casting to point light, as light is missing the position attr and typescript complains.
+            var light = scene.getLightByID(parsedShadowGenerator.lightId);
+            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
+            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
+                var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
+                meshes.forEach(function (mesh) {
+                    shadowGenerator.getShadowMap().renderList.push(mesh);
+                });
+            }
+            if (parsedShadowGenerator.usePoissonSampling) {
+                shadowGenerator.usePoissonSampling = true;
+            }
+            else if (parsedShadowGenerator.useVarianceShadowMap) {
+                shadowGenerator.useVarianceShadowMap = true;
+            }
+            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
+                shadowGenerator.useBlurVarianceShadowMap = true;
+                if (parsedShadowGenerator.blurScale) {
+                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
+                }
+                if (parsedShadowGenerator.blurBoxOffset) {
+                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
+                }
+            }
+            if (parsedShadowGenerator.bias !== undefined) {
+                shadowGenerator.bias = parsedShadowGenerator.bias;
+            }
+            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
+            return shadowGenerator;
+        };
+        ShadowGenerator._FILTER_NONE = 0;
+        ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
+        ShadowGenerator._FILTER_POISSONSAMPLING = 2;
+        ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
+        return ShadowGenerator;
+    })();
+    BABYLON.ShadowGenerator = ShadowGenerator;
+})(BABYLON || (BABYLON = {}));

+ 129 - 130
src/Lights/babylon.directionalLight.js

@@ -1,130 +1,129 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var DirectionalLight = (function (_super) {
-        __extends(DirectionalLight, _super);
-        function DirectionalLight(name, direction, scene) {
-            _super.call(this, name, scene);
-            this.shadowOrthoScale = 0.5;
-            this.autoUpdateExtends = true;
-            // Cache
-            this._orthoLeft = Number.MAX_VALUE;
-            this._orthoRight = Number.MIN_VALUE;
-            this._orthoTop = Number.MIN_VALUE;
-            this._orthoBottom = Number.MAX_VALUE;
-            this.position = direction.scale(-1);
-            this.direction = direction;
-        }
-        DirectionalLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        DirectionalLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
-            return this.direction;
-        };
-        DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            // Check extends
-            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
-                var tempVector3 = BABYLON.Vector3.Zero();
-                this._orthoLeft = Number.MAX_VALUE;
-                this._orthoRight = Number.MIN_VALUE;
-                this._orthoTop = Number.MIN_VALUE;
-                this._orthoBottom = Number.MAX_VALUE;
-                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
-                    var mesh = renderList[meshIndex];
-                    if (!mesh) {
-                        continue;
-                    }
-                    var boundingInfo = mesh.getBoundingInfo();
-                    if (!boundingInfo) {
-                        continue;
-                    }
-                    var boundingBox = boundingInfo.boundingBox;
-                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
-                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
-                        if (tempVector3.x < this._orthoLeft)
-                            this._orthoLeft = tempVector3.x;
-                        if (tempVector3.y < this._orthoBottom)
-                            this._orthoBottom = tempVector3.y;
-                        if (tempVector3.x > this._orthoRight)
-                            this._orthoRight = tempVector3.x;
-                        if (tempVector3.y > this._orthoTop)
-                            this._orthoTop = tempVector3.y;
-                    }
-                }
-            }
-            var xOffset = this._orthoRight - this._orthoLeft;
-            var yOffset = this._orthoTop - this._orthoBottom;
-            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
-        };
-        DirectionalLight.prototype.supportsVSM = function () {
-            return true;
-        };
-        DirectionalLight.prototype.needRefreshPerFrame = function () {
-            return true;
-        };
-        DirectionalLight.prototype.needCube = function () {
-            return false;
-        };
-        DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
-            return this.direction;
-        };
-        DirectionalLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._transformedDirection) {
-                    this._transformedDirection = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
-                effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
-                return;
-            }
-            effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
-        };
-        DirectionalLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        DirectionalLight.prototype.getTypeID = function () {
-            return 1;
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], DirectionalLight.prototype, "position", void 0);
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], DirectionalLight.prototype, "direction", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
-        return DirectionalLight;
-    }(BABYLON.Light));
-    BABYLON.DirectionalLight = DirectionalLight;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.directionalLight.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var DirectionalLight = (function (_super) {
+        __extends(DirectionalLight, _super);
+        function DirectionalLight(name, direction, scene) {
+            _super.call(this, name, scene);
+            this.shadowOrthoScale = 0.5;
+            this.autoUpdateExtends = true;
+            // Cache
+            this._orthoLeft = Number.MAX_VALUE;
+            this._orthoRight = Number.MIN_VALUE;
+            this._orthoTop = Number.MIN_VALUE;
+            this._orthoBottom = Number.MAX_VALUE;
+            this.position = direction.scale(-1);
+            this.direction = direction;
+        }
+        DirectionalLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        DirectionalLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
+            return this.direction;
+        };
+        DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            // Check extends
+            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
+                var tempVector3 = BABYLON.Vector3.Zero();
+                this._orthoLeft = Number.MAX_VALUE;
+                this._orthoRight = Number.MIN_VALUE;
+                this._orthoTop = Number.MIN_VALUE;
+                this._orthoBottom = Number.MAX_VALUE;
+                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
+                    var mesh = renderList[meshIndex];
+                    if (!mesh) {
+                        continue;
+                    }
+                    var boundingInfo = mesh.getBoundingInfo();
+                    if (!boundingInfo) {
+                        continue;
+                    }
+                    var boundingBox = boundingInfo.boundingBox;
+                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
+                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
+                        if (tempVector3.x < this._orthoLeft)
+                            this._orthoLeft = tempVector3.x;
+                        if (tempVector3.y < this._orthoBottom)
+                            this._orthoBottom = tempVector3.y;
+                        if (tempVector3.x > this._orthoRight)
+                            this._orthoRight = tempVector3.x;
+                        if (tempVector3.y > this._orthoTop)
+                            this._orthoTop = tempVector3.y;
+                    }
+                }
+            }
+            var xOffset = this._orthoRight - this._orthoLeft;
+            var yOffset = this._orthoTop - this._orthoBottom;
+            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
+        };
+        DirectionalLight.prototype.supportsVSM = function () {
+            return true;
+        };
+        DirectionalLight.prototype.needRefreshPerFrame = function () {
+            return true;
+        };
+        DirectionalLight.prototype.needCube = function () {
+            return false;
+        };
+        DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
+            return this.direction;
+        };
+        DirectionalLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._transformedDirection) {
+                    this._transformedDirection = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
+                effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
+                return;
+            }
+            effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
+        };
+        DirectionalLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        DirectionalLight.prototype.getTypeID = function () {
+            return 1;
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], DirectionalLight.prototype, "position", void 0);
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], DirectionalLight.prototype, "direction", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
+        return DirectionalLight;
+    })(BABYLON.Light);
+    BABYLON.DirectionalLight = DirectionalLight;
+})(BABYLON || (BABYLON = {}));

+ 51 - 52
src/Lights/babylon.hemisphericLight.js

@@ -1,52 +1,51 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var HemisphericLight = (function (_super) {
-        __extends(HemisphericLight, _super);
-        function HemisphericLight(name, direction, scene) {
-            _super.call(this, name, scene);
-            this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
-            this.direction = direction;
-        }
-        HemisphericLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
-            return this.direction;
-        };
-        HemisphericLight.prototype.getShadowGenerator = function () {
-            return null;
-        };
-        HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
-            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
-            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
-            effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
-        };
-        HemisphericLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            return this._worldMatrix;
-        };
-        HemisphericLight.prototype.getTypeID = function () {
-            return 3;
-        };
-        __decorate([
-            BABYLON.serializeAsColor3()
-        ], HemisphericLight.prototype, "groundColor", void 0);
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], HemisphericLight.prototype, "direction", void 0);
-        return HemisphericLight;
-    }(BABYLON.Light));
-    BABYLON.HemisphericLight = HemisphericLight;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.hemisphericLight.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var HemisphericLight = (function (_super) {
+        __extends(HemisphericLight, _super);
+        function HemisphericLight(name, direction, scene) {
+            _super.call(this, name, scene);
+            this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
+            this.direction = direction;
+        }
+        HemisphericLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
+            return this.direction;
+        };
+        HemisphericLight.prototype.getShadowGenerator = function () {
+            return null;
+        };
+        HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
+            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
+            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
+            effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
+        };
+        HemisphericLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            return this._worldMatrix;
+        };
+        HemisphericLight.prototype.getTypeID = function () {
+            return 3;
+        };
+        __decorate([
+            BABYLON.serializeAsColor3()
+        ], HemisphericLight.prototype, "groundColor", void 0);
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], HemisphericLight.prototype, "direction", void 0);
+        return HemisphericLight;
+    })(BABYLON.Light);
+    BABYLON.HemisphericLight = HemisphericLight;
+})(BABYLON || (BABYLON = {}));

+ 194 - 195
src/Lights/babylon.light.js

@@ -1,195 +1,194 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Light = (function (_super) {
-        __extends(Light, _super);
-        function Light(name, scene) {
-            _super.call(this, name, scene);
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.intensity = 1.0;
-            this.range = Number.MAX_VALUE;
-            this.includeOnlyWithLayerMask = 0;
-            this.includedOnlyMeshes = new Array();
-            this.excludedMeshes = new Array();
-            this.excludeWithLayerMask = 0;
-            // PBR Properties.
-            this.radius = 0.00001;
-            this._excludedMeshesIds = new Array();
-            this._includedOnlyMeshesIds = new Array();
-            scene.addLight(this);
-        }
-        /**
-         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
-         */
-        Light.prototype.toString = function (fullDetails) {
-            var ret = "Name: " + this.name;
-            ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
-            if (this.animations) {
-                for (var i = 0; i < this.animations.length; i++) {
-                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
-                }
-            }
-            if (fullDetails) {
-            }
-            return ret;
-        };
-        Light.prototype.getShadowGenerator = function () {
-            return this._shadowGenerator;
-        };
-        Light.prototype.getAbsolutePosition = function () {
-            return BABYLON.Vector3.Zero();
-        };
-        Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
-        };
-        Light.prototype._getWorldMatrix = function () {
-            return BABYLON.Matrix.Identity();
-        };
-        Light.prototype.canAffectMesh = function (mesh) {
-            if (!mesh) {
-                return true;
-            }
-            if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
-                return false;
-            }
-            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
-                return false;
-            }
-            if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
-                return false;
-            }
-            if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
-                return false;
-            }
-            return true;
-        };
-        Light.prototype.getWorldMatrix = function () {
-            this._currentRenderId = this.getScene().getRenderId();
-            var worldMatrix = this._getWorldMatrix();
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._parentedWorldMatrix) {
-                    this._parentedWorldMatrix = BABYLON.Matrix.Identity();
-                }
-                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
-                this._markSyncedWithParent();
-                return this._parentedWorldMatrix;
-            }
-            return worldMatrix;
-        };
-        Light.prototype.dispose = function () {
-            if (this._shadowGenerator) {
-                this._shadowGenerator.dispose();
-                this._shadowGenerator = null;
-            }
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            this.getScene().removeLight(this);
-            _super.prototype.dispose.call(this);
-        };
-        Light.prototype.getTypeID = function () {
-            return 0;
-        };
-        Light.prototype.clone = function (name) {
-            return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
-        };
-        Light.prototype.serialize = function () {
-            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
-            // Type
-            serializationObject.type = this.getTypeID();
-            // Parent
-            if (this.parent) {
-                serializationObject.parentId = this.parent.id;
-            }
-            // Inclusion / exclusions
-            if (this.excludedMeshes.length > 0) {
-                serializationObject.excludedMeshesIds = [];
-                this.excludedMeshes.forEach(function (mesh) {
-                    serializationObject.excludedMeshesIds.push(mesh.id);
-                });
-            }
-            if (this.includedOnlyMeshes.length > 0) {
-                serializationObject.includedOnlyMeshesIds = [];
-                this.includedOnlyMeshes.forEach(function (mesh) {
-                    serializationObject.includedOnlyMeshesIds.push(mesh.id);
-                });
-            }
-            // Animations  
-            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
-            serializationObject.ranges = this.serializeAnimationRanges();
-            return serializationObject;
-        };
-        Light.GetConstructorFromName = function (type, name, scene) {
-            switch (type) {
-                case 0:
-                    return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
-                case 1:
-                    return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
-                case 2:
-                    return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
-                case 3:
-                    return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
-            }
-        };
-        Light.Parse = function (parsedLight, scene) {
-            var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
-            // Inclusion / exclusions
-            if (parsedLight.excludedMeshesIds) {
-                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
-            }
-            if (parsedLight.includedOnlyMeshesIds) {
-                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
-            }
-            // Parent
-            if (parsedLight.parentId) {
-                light._waitingParentId = parsedLight.parentId;
-            }
-            // Animations
-            if (parsedLight.animations) {
-                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedLight.animations[animationIndex];
-                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                }
-                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
-            }
-            if (parsedLight.autoAnimate) {
-                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
-            }
-            return light;
-        };
-        __decorate([
-            BABYLON.serializeAsColor3()
-        ], Light.prototype, "diffuse", void 0);
-        __decorate([
-            BABYLON.serializeAsColor3()
-        ], Light.prototype, "specular", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Light.prototype, "intensity", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Light.prototype, "range", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Light.prototype, "includeOnlyWithLayerMask", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Light.prototype, "excludeWithLayerMask", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Light.prototype, "radius", void 0);
-        return Light;
-    }(BABYLON.Node));
-    BABYLON.Light = Light;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.light.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Light = (function (_super) {
+        __extends(Light, _super);
+        function Light(name, scene) {
+            _super.call(this, name, scene);
+            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
+            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
+            this.intensity = 1.0;
+            this.range = Number.MAX_VALUE;
+            this.includeOnlyWithLayerMask = 0;
+            this.includedOnlyMeshes = new Array();
+            this.excludedMeshes = new Array();
+            this.excludeWithLayerMask = 0;
+            // PBR Properties.
+            this.radius = 0.00001;
+            this._excludedMeshesIds = new Array();
+            this._includedOnlyMeshesIds = new Array();
+            scene.addLight(this);
+        }
+        /**
+         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
+         */
+        Light.prototype.toString = function (fullDetails) {
+            var ret = "Name: " + this.name;
+            ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
+            if (this.animations) {
+                for (var i = 0; i < this.animations.length; i++) {
+                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
+                }
+            }
+            if (fullDetails) {
+            }
+            return ret;
+        };
+        Light.prototype.getShadowGenerator = function () {
+            return this._shadowGenerator;
+        };
+        Light.prototype.getAbsolutePosition = function () {
+            return BABYLON.Vector3.Zero();
+        };
+        Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
+        };
+        Light.prototype._getWorldMatrix = function () {
+            return BABYLON.Matrix.Identity();
+        };
+        Light.prototype.canAffectMesh = function (mesh) {
+            if (!mesh) {
+                return true;
+            }
+            if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
+                return false;
+            }
+            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
+                return false;
+            }
+            if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
+                return false;
+            }
+            if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
+                return false;
+            }
+            return true;
+        };
+        Light.prototype.getWorldMatrix = function () {
+            this._currentRenderId = this.getScene().getRenderId();
+            var worldMatrix = this._getWorldMatrix();
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._parentedWorldMatrix) {
+                    this._parentedWorldMatrix = BABYLON.Matrix.Identity();
+                }
+                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
+                this._markSyncedWithParent();
+                return this._parentedWorldMatrix;
+            }
+            return worldMatrix;
+        };
+        Light.prototype.dispose = function () {
+            if (this._shadowGenerator) {
+                this._shadowGenerator.dispose();
+                this._shadowGenerator = null;
+            }
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            this.getScene().removeLight(this);
+            _super.prototype.dispose.call(this);
+        };
+        Light.prototype.getTypeID = function () {
+            return 0;
+        };
+        Light.prototype.clone = function (name) {
+            return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
+        };
+        Light.prototype.serialize = function () {
+            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
+            // Type
+            serializationObject.type = this.getTypeID();
+            // Parent
+            if (this.parent) {
+                serializationObject.parentId = this.parent.id;
+            }
+            // Inclusion / exclusions
+            if (this.excludedMeshes.length > 0) {
+                serializationObject.excludedMeshesIds = [];
+                this.excludedMeshes.forEach(function (mesh) {
+                    serializationObject.excludedMeshesIds.push(mesh.id);
+                });
+            }
+            if (this.includedOnlyMeshes.length > 0) {
+                serializationObject.includedOnlyMeshesIds = [];
+                this.includedOnlyMeshes.forEach(function (mesh) {
+                    serializationObject.includedOnlyMeshesIds.push(mesh.id);
+                });
+            }
+            // Animations  
+            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
+            serializationObject.ranges = this.serializeAnimationRanges();
+            return serializationObject;
+        };
+        Light.GetConstructorFromName = function (type, name, scene) {
+            switch (type) {
+                case 0:
+                    return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
+                case 1:
+                    return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
+                case 2:
+                    return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
+                case 3:
+                    return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
+            }
+        };
+        Light.Parse = function (parsedLight, scene) {
+            var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
+            // Inclusion / exclusions
+            if (parsedLight.excludedMeshesIds) {
+                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
+            }
+            if (parsedLight.includedOnlyMeshesIds) {
+                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
+            }
+            // Parent
+            if (parsedLight.parentId) {
+                light._waitingParentId = parsedLight.parentId;
+            }
+            // Animations
+            if (parsedLight.animations) {
+                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedLight.animations[animationIndex];
+                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                }
+                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
+            }
+            if (parsedLight.autoAnimate) {
+                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
+            }
+            return light;
+        };
+        __decorate([
+            BABYLON.serializeAsColor3()
+        ], Light.prototype, "diffuse", void 0);
+        __decorate([
+            BABYLON.serializeAsColor3()
+        ], Light.prototype, "specular", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Light.prototype, "intensity", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Light.prototype, "range", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Light.prototype, "includeOnlyWithLayerMask", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Light.prototype, "excludeWithLayerMask", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Light.prototype, "radius", void 0);
+        return Light;
+    })(BABYLON.Node);
+    BABYLON.Light = Light;
+})(BABYLON || (BABYLON = {}));

+ 87 - 88
src/Lights/babylon.pointLight.js

@@ -1,88 +1,87 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var PointLight = (function (_super) {
-        __extends(PointLight, _super);
-        function PointLight(name, position, scene) {
-            _super.call(this, name, scene);
-            this.position = position;
-        }
-        PointLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        PointLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
-            if (this.parent && this.parent.getWorldMatrix) {
-                this.computeTransformedPosition();
-                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
-                return;
-            }
-            effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
-        };
-        PointLight.prototype.needCube = function () {
-            return true;
-        };
-        PointLight.prototype.supportsVSM = function () {
-            return false;
-        };
-        PointLight.prototype.needRefreshPerFrame = function () {
-            return false;
-        };
-        PointLight.prototype.getShadowDirection = function (faceIndex) {
-            switch (faceIndex) {
-                case 0:
-                    return new BABYLON.Vector3(1, 0, 0);
-                case 1:
-                    return new BABYLON.Vector3(-1, 0, 0);
-                case 2:
-                    return new BABYLON.Vector3(0, -1, 0);
-                case 3:
-                    return new BABYLON.Vector3(0, 1, 0);
-                case 4:
-                    return new BABYLON.Vector3(0, 0, 1);
-                case 5:
-                    return new BABYLON.Vector3(0, 0, -1);
-            }
-            return BABYLON.Vector3.Zero();
-        };
-        PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
-        };
-        PointLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        PointLight.prototype.getTypeID = function () {
-            return 0;
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], PointLight.prototype, "position", void 0);
-        return PointLight;
-    }(BABYLON.Light));
-    BABYLON.PointLight = PointLight;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.pointLight.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var PointLight = (function (_super) {
+        __extends(PointLight, _super);
+        function PointLight(name, position, scene) {
+            _super.call(this, name, scene);
+            this.position = position;
+        }
+        PointLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        PointLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
+            if (this.parent && this.parent.getWorldMatrix) {
+                this.computeTransformedPosition();
+                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
+                return;
+            }
+            effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
+        };
+        PointLight.prototype.needCube = function () {
+            return true;
+        };
+        PointLight.prototype.supportsVSM = function () {
+            return false;
+        };
+        PointLight.prototype.needRefreshPerFrame = function () {
+            return false;
+        };
+        PointLight.prototype.getShadowDirection = function (faceIndex) {
+            switch (faceIndex) {
+                case 0:
+                    return new BABYLON.Vector3(1, 0, 0);
+                case 1:
+                    return new BABYLON.Vector3(-1, 0, 0);
+                case 2:
+                    return new BABYLON.Vector3(0, -1, 0);
+                case 3:
+                    return new BABYLON.Vector3(0, 1, 0);
+                case 4:
+                    return new BABYLON.Vector3(0, 0, 1);
+                case 5:
+                    return new BABYLON.Vector3(0, 0, -1);
+            }
+            return BABYLON.Vector3.Zero();
+        };
+        PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
+        };
+        PointLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        PointLight.prototype.getTypeID = function () {
+            return 0;
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], PointLight.prototype, "position", void 0);
+        return PointLight;
+    })(BABYLON.Light);
+    BABYLON.PointLight = PointLight;
+})(BABYLON || (BABYLON = {}));

+ 98 - 99
src/Lights/babylon.spotLight.js

@@ -1,99 +1,98 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var SpotLight = (function (_super) {
-        __extends(SpotLight, _super);
-        function SpotLight(name, position, direction, angle, exponent, scene) {
-            _super.call(this, name, scene);
-            this.position = position;
-            this.direction = direction;
-            this.angle = angle;
-            this.exponent = exponent;
-        }
-        SpotLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
-        };
-        SpotLight.prototype.needCube = function () {
-            return false;
-        };
-        SpotLight.prototype.supportsVSM = function () {
-            return true;
-        };
-        SpotLight.prototype.needRefreshPerFrame = function () {
-            return false;
-        };
-        SpotLight.prototype.getShadowDirection = function (faceIndex) {
-            return this.direction;
-        };
-        SpotLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
-            return this.direction;
-        };
-        SpotLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
-            var normalizeDirection;
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._transformedDirection) {
-                    this._transformedDirection = BABYLON.Vector3.Zero();
-                }
-                this.computeTransformedPosition();
-                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
-                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
-                normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
-            }
-            else {
-                effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
-                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
-            }
-            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
-        };
-        SpotLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        SpotLight.prototype.getTypeID = function () {
-            return 2;
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], SpotLight.prototype, "position", void 0);
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], SpotLight.prototype, "direction", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], SpotLight.prototype, "angle", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], SpotLight.prototype, "exponent", void 0);
-        return SpotLight;
-    }(BABYLON.Light));
-    BABYLON.SpotLight = SpotLight;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.spotLight.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var SpotLight = (function (_super) {
+        __extends(SpotLight, _super);
+        function SpotLight(name, position, direction, angle, exponent, scene) {
+            _super.call(this, name, scene);
+            this.position = position;
+            this.direction = direction;
+            this.angle = angle;
+            this.exponent = exponent;
+        }
+        SpotLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
+        };
+        SpotLight.prototype.needCube = function () {
+            return false;
+        };
+        SpotLight.prototype.supportsVSM = function () {
+            return true;
+        };
+        SpotLight.prototype.needRefreshPerFrame = function () {
+            return false;
+        };
+        SpotLight.prototype.getShadowDirection = function (faceIndex) {
+            return this.direction;
+        };
+        SpotLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
+            return this.direction;
+        };
+        SpotLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
+            var normalizeDirection;
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._transformedDirection) {
+                    this._transformedDirection = BABYLON.Vector3.Zero();
+                }
+                this.computeTransformedPosition();
+                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
+                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
+                normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
+            }
+            else {
+                effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
+                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
+            }
+            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
+        };
+        SpotLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        SpotLight.prototype.getTypeID = function () {
+            return 2;
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], SpotLight.prototype, "position", void 0);
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], SpotLight.prototype, "direction", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], SpotLight.prototype, "angle", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], SpotLight.prototype, "exponent", void 0);
+        return SpotLight;
+    })(BABYLON.Light);
+    BABYLON.SpotLight = SpotLight;
+})(BABYLON || (BABYLON = {}));

+ 491 - 492
src/Loading/Plugins/babylon.babylonFileLoader.js

@@ -1,492 +1,491 @@
-var BABYLON;
-(function (BABYLON) {
-    var Internals;
-    (function (Internals) {
-        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
-            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                var parsedMaterial = parsedData.materials[index];
-                if (parsedMaterial.id === id) {
-                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                }
-            }
-            return null;
-        };
-        var isDescendantOf = function (mesh, names, hierarchyIds) {
-            names = (names instanceof Array) ? names : [names];
-            for (var i in names) {
-                if (mesh.name === names[i]) {
-                    hierarchyIds.push(mesh.id);
-                    return true;
-                }
-            }
-            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
-                hierarchyIds.push(mesh.id);
-                return true;
-            }
-            return false;
-        };
-        var logOperation = function (operation, producer) {
-            return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
-        };
-        BABYLON.SceneLoader.RegisterPlugin({
-            extensions: ".babylon",
-            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
-                // 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 = "importMesh has failed JSON parse";
-                try {
-                    var parsedData = JSON.parse(data);
-                    log = "";
-                    var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
-                    var loadedSkeletonsIds = [];
-                    var loadedMaterialsIds = [];
-                    var hierarchyIds = [];
-                    var index;
-                    var cache;
-                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                        var parsedMesh = parsedData.meshes[index];
-                        if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
-                            if (meshesNames instanceof Array) {
-                                // Remove found mesh name from list.
-                                delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
-                            }
-                            //Geometry?
-                            if (parsedMesh.geometryId) {
-                                //does the file contain geometries?
-                                if (parsedData.geometries) {
-                                    //find the correct geometry and add it to the scene
-                                    var found = false;
-                                    ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
-                                        if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
-                                            return;
-                                        }
-                                        else {
-                                            parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
-                                                if (parsedGeometryData.id === parsedMesh.geometryId) {
-                                                    switch (geometryType) {
-                                                        case "boxes":
-                                                            BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "spheres":
-                                                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "cylinders":
-                                                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "toruses":
-                                                            BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "grounds":
-                                                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "planes":
-                                                            BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "torusKnots":
-                                                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
-                                                            break;
-                                                        case "vertexData":
-                                                            BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
-                                                            break;
-                                                    }
-                                                    found = true;
-                                                }
-                                            });
-                                        }
-                                    });
-                                    if (!found) {
-                                        BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
-                                    }
-                                }
-                            }
-                            // Material ?
-                            if (parsedMesh.materialId) {
-                                var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
-                                if (!materialFound && parsedData.multiMaterials) {
-                                    for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
-                                        var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
-                                        if (parsedMultiMaterial.id === parsedMesh.materialId) {
-                                            for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
-                                                var subMatId = parsedMultiMaterial.materials[matIndex];
-                                                loadedMaterialsIds.push(subMatId);
-                                                var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
-                                                log += "\n\tMaterial " + mat.toString(fullDetails);
-                                            }
-                                            loadedMaterialsIds.push(parsedMultiMaterial.id);
-                                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                                            materialFound = true;
-                                            log += "\n\tMulti-Material " + mmat.toString(fullDetails);
-                                            break;
-                                        }
-                                    }
-                                }
-                                if (!materialFound) {
-                                    loadedMaterialsIds.push(parsedMesh.materialId);
-                                    var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
-                                    if (!mat) {
-                                        BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
-                                    }
-                                    else {
-                                        log += "\n\tMaterial " + mat.toString(fullDetails);
-                                    }
-                                }
-                            }
-                            // Skeleton ?
-                            if (parsedMesh.skeletonId > -1 && scene.skeletons) {
-                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
-                                if (!skeletonAlreadyLoaded) {
-                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
-                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
-                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
-                                            skeletons.push(skeleton);
-                                            loadedSkeletonsIds.push(parsedSkeleton.id);
-                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
-                                        }
-                                    }
-                                }
-                            }
-                            var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                            meshes.push(mesh);
-                            log += "\n\tMesh " + mesh.toString(fullDetails);
-                        }
-                    }
-                    // Connecting parents
-                    var currentMesh;
-                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                        currentMesh = scene.meshes[index];
-                        if (currentMesh._waitingParentId) {
-                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
-                            currentMesh._waitingParentId = undefined;
-                        }
-                    }
-                    // freeze and compute world matrix application
-                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                        currentMesh = scene.meshes[index];
-                        if (currentMesh._waitingFreezeWorldMatrix) {
-                            currentMesh.freezeWorldMatrix();
-                            currentMesh._waitingFreezeWorldMatrix = undefined;
-                        }
-                        else {
-                            currentMesh.computeWorldMatrix(true);
-                        }
-                    }
-                    // Particles
-                    if (parsedData.particleSystems) {
-                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                            var parsedParticleSystem = parsedData.particleSystems[index];
-                            if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                                particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
-                            }
-                        }
-                    }
-                    return true;
-                }
-                catch (err) {
-                    BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
-                    log = null;
-                    throw err;
-                }
-                finally {
-                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
-                        BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
-                    }
-                }
-            },
-            load: function (scene, data, rootUrl) {
-                // 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 = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
-                    // Scene
-                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
-                    scene.autoClear = parsedData.autoClear;
-                    scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
-                    scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
-                    if (parsedData.gravity) {
-                        scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
-                    }
-                    // Fog
-                    if (parsedData.fogMode && parsedData.fogMode !== 0) {
-                        scene.fogMode = parsedData.fogMode;
-                        scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
-                        scene.fogStart = parsedData.fogStart;
-                        scene.fogEnd = parsedData.fogEnd;
-                        scene.fogDensity = parsedData.fogDensity;
-                        log += "\tFog mode for scene:  ";
-                        switch (scene.fogMode) {
-                            // getters not compiling, so using hardcoded
-                            case 1:
-                                log += "exp\n";
-                                break;
-                            case 2:
-                                log += "exp2\n";
-                                break;
-                            case 3:
-                                log += "linear\n";
-                                break;
-                        }
-                    }
-                    //Physics
-                    if (parsedData.physicsEnabled) {
-                        var physicsPlugin;
-                        if (parsedData.physicsEngine === "cannon") {
-                            physicsPlugin = new BABYLON.CannonJSPlugin();
-                        }
-                        else if (parsedData.physicsEngine === "oimo") {
-                            physicsPlugin = new BABYLON.OimoJSPlugin();
-                        }
-                        log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
-                        //else - default engine, which is currently oimo
-                        var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
-                        scene.enablePhysics(physicsGravity, physicsPlugin);
-                    }
-                    //collisions, if defined. otherwise, default is true
-                    if (parsedData.collisionsEnabled != undefined) {
-                        scene.collisionsEnabled = parsedData.collisionsEnabled;
-                    }
-                    scene.workerCollisions = !!parsedData.workerCollisions;
-                    var index;
-                    var cache;
-                    // Lights
-                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
-                        var parsedLight = parsedData.lights[index];
-                        var light = BABYLON.Light.Parse(parsedLight, scene);
-                        log += (index === 0 ? "\n\tLights:" : "");
-                        log += "\n\t\t" + light.toString(fullDetails);
-                    }
-                    // Animations
-                    if (parsedData.animations) {
-                        for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
-                            var parsedAnimation = parsedData.animations[index];
-                            var animation = BABYLON.Animation.Parse(parsedAnimation);
-                            scene.animations.push(animation);
-                            log += (index === 0 ? "\n\tAnimations:" : "");
-                            log += "\n\t\t" + animation.toString(fullDetails);
-                        }
-                    }
-                    if (parsedData.autoAnimate) {
-                        scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
-                    }
-                    // Materials
-                    if (parsedData.materials) {
-                        for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                            var parsedMaterial = parsedData.materials[index];
-                            var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                            log += (index === 0 ? "\n\tMaterials:" : "");
-                            log += "\n\t\t" + mat.toString(fullDetails);
-                        }
-                    }
-                    if (parsedData.multiMaterials) {
-                        for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
-                            var parsedMultiMaterial = parsedData.multiMaterials[index];
-                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                            log += (index === 0 ? "\n\tMultiMaterials:" : "");
-                            log += "\n\t\t" + mmat.toString(fullDetails);
-                        }
-                    }
-                    // Skeletons
-                    if (parsedData.skeletons) {
-                        for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
-                            var parsedSkeleton = parsedData.skeletons[index];
-                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
-                            log += (index === 0 ? "\n\tSkeletons:" : "");
-                            log += "\n\t\t" + skeleton.toString(fullDetails);
-                        }
-                    }
-                    // Geometries
-                    var geometries = parsedData.geometries;
-                    if (geometries) {
-                        // Boxes
-                        var boxes = geometries.boxes;
-                        if (boxes) {
-                            for (index = 0, cache = boxes.length; index < cache; index++) {
-                                var parsedBox = boxes[index];
-                                BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
-                            }
-                        }
-                        // Spheres
-                        var spheres = geometries.spheres;
-                        if (spheres) {
-                            for (index = 0, cache = spheres.length; index < cache; index++) {
-                                var parsedSphere = spheres[index];
-                                BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
-                            }
-                        }
-                        // Cylinders
-                        var cylinders = geometries.cylinders;
-                        if (cylinders) {
-                            for (index = 0, cache = cylinders.length; index < cache; index++) {
-                                var parsedCylinder = cylinders[index];
-                                BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
-                            }
-                        }
-                        // Toruses
-                        var toruses = geometries.toruses;
-                        if (toruses) {
-                            for (index = 0, cache = toruses.length; index < cache; index++) {
-                                var parsedTorus = toruses[index];
-                                BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
-                            }
-                        }
-                        // Grounds
-                        var grounds = geometries.grounds;
-                        if (grounds) {
-                            for (index = 0, cache = grounds.length; index < cache; index++) {
-                                var parsedGround = grounds[index];
-                                BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
-                            }
-                        }
-                        // Planes
-                        var planes = geometries.planes;
-                        if (planes) {
-                            for (index = 0, cache = planes.length; index < cache; index++) {
-                                var parsedPlane = planes[index];
-                                BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
-                            }
-                        }
-                        // TorusKnots
-                        var torusKnots = geometries.torusKnots;
-                        if (torusKnots) {
-                            for (index = 0, cache = torusKnots.length; index < cache; index++) {
-                                var parsedTorusKnot = torusKnots[index];
-                                BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
-                            }
-                        }
-                        // VertexData
-                        var vertexData = geometries.vertexData;
-                        if (vertexData) {
-                            for (index = 0, cache = vertexData.length; index < cache; index++) {
-                                var parsedVertexData = vertexData[index];
-                                BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
-                            }
-                        }
-                    }
-                    // Meshes
-                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                        var parsedMesh = parsedData.meshes[index];
-                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                        log += (index === 0 ? "\n\tMeshes:" : "");
-                        log += "\n\t\t" + mesh.toString(fullDetails);
-                    }
-                    // Cameras
-                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
-                        var parsedCamera = parsedData.cameras[index];
-                        var camera = BABYLON.Camera.Parse(parsedCamera, scene);
-                        log += (index === 0 ? "\n\tCameras:" : "");
-                        log += "\n\t\t" + camera.toString(fullDetails);
-                    }
-                    if (parsedData.activeCameraID) {
-                        scene.setActiveCameraByID(parsedData.activeCameraID);
-                    }
-                    // 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 = undefined;
-                        }
-                    }
-                    for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                        var light = scene.lights[index];
-                        if (light._waitingParentId) {
-                            light.parent = scene.getLastEntryByID(light._waitingParentId);
-                            light._waitingParentId = undefined;
-                        }
-                    }
-                    // Sounds
-                    var loadedSounds = [];
-                    var loadedSound;
-                    if (BABYLON.AudioEngine && parsedData.sounds) {
-                        for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
-                            var parsedSound = parsedData.sounds[index];
-                            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                                if (!parsedSound.url)
-                                    parsedSound.url = parsedSound.name;
-                                if (!loadedSounds[parsedSound.url]) {
-                                    loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
-                                    loadedSounds[parsedSound.url] = loadedSound;
-                                }
-                                else {
-                                    BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
-                                }
-                            }
-                            else {
-                                var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
-                            }
-                        }
-                    }
-                    loadedSounds = [];
-                    // Connect parents & children and parse actions
-                    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 = undefined;
-                        }
-                        if (mesh._waitingActions) {
-                            BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
-                            mesh._waitingActions = undefined;
-                        }
-                    }
-                    // 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 = undefined;
-                        }
-                        else {
-                            currentMesh.computeWorldMatrix(true);
-                        }
-                    }
-                    // Particles Systems
-                    if (parsedData.particleSystems) {
-                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                            var parsedParticleSystem = parsedData.particleSystems[index];
-                            BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
-                        }
-                    }
-                    // Lens flares
-                    if (parsedData.lensFlareSystems) {
-                        for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
-                            var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                            BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
-                        }
-                    }
-                    // Shadows
-                    if (parsedData.shadowGenerators) {
-                        for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
-                            var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                            BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
-                        }
-                    }
-                    // Actions (scene)
-                    if (parsedData.actions) {
-                        BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
-                    }
-                    // Finish
-                    return true;
-                }
-                catch (err) {
-                    BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
-                    log = null;
-                    throw err;
-                }
-                finally {
-                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
-                        BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
-                    }
-                }
-            }
-        });
-    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.babylonFileLoader.js.map
+var BABYLON;
+(function (BABYLON) {
+    var Internals;
+    (function (Internals) {
+        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
+            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                var parsedMaterial = parsedData.materials[index];
+                if (parsedMaterial.id === id) {
+                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                }
+            }
+            return null;
+        };
+        var isDescendantOf = function (mesh, names, hierarchyIds) {
+            names = (names instanceof Array) ? names : [names];
+            for (var i in names) {
+                if (mesh.name === names[i]) {
+                    hierarchyIds.push(mesh.id);
+                    return true;
+                }
+            }
+            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
+                hierarchyIds.push(mesh.id);
+                return true;
+            }
+            return false;
+        };
+        var logOperation = function (operation, producer) {
+            return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
+        };
+        BABYLON.SceneLoader.RegisterPlugin({
+            extensions: ".babylon",
+            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
+                // 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 = "importMesh has failed JSON parse";
+                try {
+                    var parsedData = JSON.parse(data);
+                    log = "";
+                    var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
+                    var loadedSkeletonsIds = [];
+                    var loadedMaterialsIds = [];
+                    var hierarchyIds = [];
+                    var index;
+                    var cache;
+                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                        var parsedMesh = parsedData.meshes[index];
+                        if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
+                            if (meshesNames instanceof Array) {
+                                // Remove found mesh name from list.
+                                delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
+                            }
+                            //Geometry?
+                            if (parsedMesh.geometryId) {
+                                //does the file contain geometries?
+                                if (parsedData.geometries) {
+                                    //find the correct geometry and add it to the scene
+                                    var found = false;
+                                    ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
+                                        if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
+                                            return;
+                                        }
+                                        else {
+                                            parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
+                                                if (parsedGeometryData.id === parsedMesh.geometryId) {
+                                                    switch (geometryType) {
+                                                        case "boxes":
+                                                            BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "spheres":
+                                                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "cylinders":
+                                                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "toruses":
+                                                            BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "grounds":
+                                                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "planes":
+                                                            BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "torusKnots":
+                                                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
+                                                            break;
+                                                        case "vertexData":
+                                                            BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
+                                                            break;
+                                                    }
+                                                    found = true;
+                                                }
+                                            });
+                                        }
+                                    });
+                                    if (!found) {
+                                        BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
+                                    }
+                                }
+                            }
+                            // Material ?
+                            if (parsedMesh.materialId) {
+                                var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
+                                if (!materialFound && parsedData.multiMaterials) {
+                                    for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
+                                        var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
+                                        if (parsedMultiMaterial.id === parsedMesh.materialId) {
+                                            for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
+                                                var subMatId = parsedMultiMaterial.materials[matIndex];
+                                                loadedMaterialsIds.push(subMatId);
+                                                var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
+                                                log += "\n\tMaterial " + mat.toString(fullDetails);
+                                            }
+                                            loadedMaterialsIds.push(parsedMultiMaterial.id);
+                                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                                            materialFound = true;
+                                            log += "\n\tMulti-Material " + mmat.toString(fullDetails);
+                                            break;
+                                        }
+                                    }
+                                }
+                                if (!materialFound) {
+                                    loadedMaterialsIds.push(parsedMesh.materialId);
+                                    var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
+                                    if (!mat) {
+                                        BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
+                                    }
+                                    else {
+                                        log += "\n\tMaterial " + mat.toString(fullDetails);
+                                    }
+                                }
+                            }
+                            // Skeleton ?
+                            if (parsedMesh.skeletonId > -1 && scene.skeletons) {
+                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
+                                if (!skeletonAlreadyLoaded) {
+                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
+                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
+                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
+                                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
+                                            skeletons.push(skeleton);
+                                            loadedSkeletonsIds.push(parsedSkeleton.id);
+                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
+                                        }
+                                    }
+                                }
+                            }
+                            var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                            meshes.push(mesh);
+                            log += "\n\tMesh " + mesh.toString(fullDetails);
+                        }
+                    }
+                    // Connecting parents
+                    var currentMesh;
+                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                        currentMesh = scene.meshes[index];
+                        if (currentMesh._waitingParentId) {
+                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
+                            currentMesh._waitingParentId = undefined;
+                        }
+                    }
+                    // freeze and compute world matrix application
+                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                        currentMesh = scene.meshes[index];
+                        if (currentMesh._waitingFreezeWorldMatrix) {
+                            currentMesh.freezeWorldMatrix();
+                            currentMesh._waitingFreezeWorldMatrix = undefined;
+                        }
+                        else {
+                            currentMesh.computeWorldMatrix(true);
+                        }
+                    }
+                    // Particles
+                    if (parsedData.particleSystems) {
+                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                            var parsedParticleSystem = parsedData.particleSystems[index];
+                            if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
+                                particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
+                            }
+                        }
+                    }
+                    return true;
+                }
+                catch (err) {
+                    BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
+                    log = null;
+                    throw err;
+                }
+                finally {
+                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
+                        BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
+                    }
+                }
+            },
+            load: function (scene, data, rootUrl) {
+                // 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 = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
+                    // Scene
+                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
+                    scene.autoClear = parsedData.autoClear;
+                    scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
+                    scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
+                    if (parsedData.gravity) {
+                        scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
+                    }
+                    // Fog
+                    if (parsedData.fogMode && parsedData.fogMode !== 0) {
+                        scene.fogMode = parsedData.fogMode;
+                        scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
+                        scene.fogStart = parsedData.fogStart;
+                        scene.fogEnd = parsedData.fogEnd;
+                        scene.fogDensity = parsedData.fogDensity;
+                        log += "\tFog mode for scene:  ";
+                        switch (scene.fogMode) {
+                            // getters not compiling, so using hardcoded
+                            case 1:
+                                log += "exp\n";
+                                break;
+                            case 2:
+                                log += "exp2\n";
+                                break;
+                            case 3:
+                                log += "linear\n";
+                                break;
+                        }
+                    }
+                    //Physics
+                    if (parsedData.physicsEnabled) {
+                        var physicsPlugin;
+                        if (parsedData.physicsEngine === "cannon") {
+                            physicsPlugin = new BABYLON.CannonJSPlugin();
+                        }
+                        else if (parsedData.physicsEngine === "oimo") {
+                            physicsPlugin = new BABYLON.OimoJSPlugin();
+                        }
+                        log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
+                        //else - default engine, which is currently oimo
+                        var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
+                        scene.enablePhysics(physicsGravity, physicsPlugin);
+                    }
+                    //collisions, if defined. otherwise, default is true
+                    if (parsedData.collisionsEnabled != undefined) {
+                        scene.collisionsEnabled = parsedData.collisionsEnabled;
+                    }
+                    scene.workerCollisions = !!parsedData.workerCollisions;
+                    var index;
+                    var cache;
+                    // Lights
+                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
+                        var parsedLight = parsedData.lights[index];
+                        var light = BABYLON.Light.Parse(parsedLight, scene);
+                        log += (index === 0 ? "\n\tLights:" : "");
+                        log += "\n\t\t" + light.toString(fullDetails);
+                    }
+                    // Animations
+                    if (parsedData.animations) {
+                        for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
+                            var parsedAnimation = parsedData.animations[index];
+                            var animation = BABYLON.Animation.Parse(parsedAnimation);
+                            scene.animations.push(animation);
+                            log += (index === 0 ? "\n\tAnimations:" : "");
+                            log += "\n\t\t" + animation.toString(fullDetails);
+                        }
+                    }
+                    if (parsedData.autoAnimate) {
+                        scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
+                    }
+                    // Materials
+                    if (parsedData.materials) {
+                        for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                            var parsedMaterial = parsedData.materials[index];
+                            var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                            log += (index === 0 ? "\n\tMaterials:" : "");
+                            log += "\n\t\t" + mat.toString(fullDetails);
+                        }
+                    }
+                    if (parsedData.multiMaterials) {
+                        for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
+                            var parsedMultiMaterial = parsedData.multiMaterials[index];
+                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                            log += (index === 0 ? "\n\tMultiMaterials:" : "");
+                            log += "\n\t\t" + mmat.toString(fullDetails);
+                        }
+                    }
+                    // Skeletons
+                    if (parsedData.skeletons) {
+                        for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
+                            var parsedSkeleton = parsedData.skeletons[index];
+                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
+                            log += (index === 0 ? "\n\tSkeletons:" : "");
+                            log += "\n\t\t" + skeleton.toString(fullDetails);
+                        }
+                    }
+                    // Geometries
+                    var geometries = parsedData.geometries;
+                    if (geometries) {
+                        // Boxes
+                        var boxes = geometries.boxes;
+                        if (boxes) {
+                            for (index = 0, cache = boxes.length; index < cache; index++) {
+                                var parsedBox = boxes[index];
+                                BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
+                            }
+                        }
+                        // Spheres
+                        var spheres = geometries.spheres;
+                        if (spheres) {
+                            for (index = 0, cache = spheres.length; index < cache; index++) {
+                                var parsedSphere = spheres[index];
+                                BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
+                            }
+                        }
+                        // Cylinders
+                        var cylinders = geometries.cylinders;
+                        if (cylinders) {
+                            for (index = 0, cache = cylinders.length; index < cache; index++) {
+                                var parsedCylinder = cylinders[index];
+                                BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
+                            }
+                        }
+                        // Toruses
+                        var toruses = geometries.toruses;
+                        if (toruses) {
+                            for (index = 0, cache = toruses.length; index < cache; index++) {
+                                var parsedTorus = toruses[index];
+                                BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
+                            }
+                        }
+                        // Grounds
+                        var grounds = geometries.grounds;
+                        if (grounds) {
+                            for (index = 0, cache = grounds.length; index < cache; index++) {
+                                var parsedGround = grounds[index];
+                                BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
+                            }
+                        }
+                        // Planes
+                        var planes = geometries.planes;
+                        if (planes) {
+                            for (index = 0, cache = planes.length; index < cache; index++) {
+                                var parsedPlane = planes[index];
+                                BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
+                            }
+                        }
+                        // TorusKnots
+                        var torusKnots = geometries.torusKnots;
+                        if (torusKnots) {
+                            for (index = 0, cache = torusKnots.length; index < cache; index++) {
+                                var parsedTorusKnot = torusKnots[index];
+                                BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
+                            }
+                        }
+                        // VertexData
+                        var vertexData = geometries.vertexData;
+                        if (vertexData) {
+                            for (index = 0, cache = vertexData.length; index < cache; index++) {
+                                var parsedVertexData = vertexData[index];
+                                BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
+                            }
+                        }
+                    }
+                    // Meshes
+                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                        var parsedMesh = parsedData.meshes[index];
+                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                        log += (index === 0 ? "\n\tMeshes:" : "");
+                        log += "\n\t\t" + mesh.toString(fullDetails);
+                    }
+                    // Cameras
+                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
+                        var parsedCamera = parsedData.cameras[index];
+                        var camera = BABYLON.Camera.Parse(parsedCamera, scene);
+                        log += (index === 0 ? "\n\tCameras:" : "");
+                        log += "\n\t\t" + camera.toString(fullDetails);
+                    }
+                    if (parsedData.activeCameraID) {
+                        scene.setActiveCameraByID(parsedData.activeCameraID);
+                    }
+                    // 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 = undefined;
+                        }
+                    }
+                    for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                        var light = scene.lights[index];
+                        if (light._waitingParentId) {
+                            light.parent = scene.getLastEntryByID(light._waitingParentId);
+                            light._waitingParentId = undefined;
+                        }
+                    }
+                    // Sounds
+                    var loadedSounds = [];
+                    var loadedSound;
+                    if (BABYLON.AudioEngine && parsedData.sounds) {
+                        for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
+                            var parsedSound = parsedData.sounds[index];
+                            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                                if (!parsedSound.url)
+                                    parsedSound.url = parsedSound.name;
+                                if (!loadedSounds[parsedSound.url]) {
+                                    loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
+                                    loadedSounds[parsedSound.url] = loadedSound;
+                                }
+                                else {
+                                    BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
+                                }
+                            }
+                            else {
+                                var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
+                            }
+                        }
+                    }
+                    loadedSounds = [];
+                    // Connect parents & children and parse actions
+                    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 = undefined;
+                        }
+                        if (mesh._waitingActions) {
+                            BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                            mesh._waitingActions = undefined;
+                        }
+                    }
+                    // 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 = undefined;
+                        }
+                        else {
+                            currentMesh.computeWorldMatrix(true);
+                        }
+                    }
+                    // Particles Systems
+                    if (parsedData.particleSystems) {
+                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                            var parsedParticleSystem = parsedData.particleSystems[index];
+                            BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                        }
+                    }
+                    // Lens flares
+                    if (parsedData.lensFlareSystems) {
+                        for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
+                            var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                            BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                        }
+                    }
+                    // Shadows
+                    if (parsedData.shadowGenerators) {
+                        for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+                            var parsedShadowGenerator = parsedData.shadowGenerators[index];
+                            BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                        }
+                    }
+                    // Actions (scene)
+                    if (parsedData.actions) {
+                        BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
+                    }
+                    // Finish
+                    return true;
+                }
+                catch (err) {
+                    BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
+                    log = null;
+                    throw err;
+                }
+                finally {
+                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
+                        BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
+                    }
+                }
+            }
+        });
+    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
+})(BABYLON || (BABYLON = {}));

+ 263 - 264
src/Loading/babylon.sceneLoader.js

@@ -1,264 +1,263 @@
-var BABYLON;
-(function (BABYLON) {
-    var SceneLoader = (function () {
-        function SceneLoader() {
-        }
-        Object.defineProperty(SceneLoader, "NO_LOGGING", {
-            get: function () {
-                return 0;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
-            get: function () {
-                return 1;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
-            get: function () {
-                return 2;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
-            get: function () {
-                return 3;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
-            get: function () {
-                return SceneLoader._ForceFullSceneLoadingForIncremental;
-            },
-            set: function (value) {
-                SceneLoader._ForceFullSceneLoadingForIncremental = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
-            get: function () {
-                return SceneLoader._ShowLoadingScreen;
-            },
-            set: function (value) {
-                SceneLoader._ShowLoadingScreen = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "loggingLevel", {
-            get: function () {
-                return SceneLoader._loggingLevel;
-            },
-            set: function (value) {
-                SceneLoader._loggingLevel = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SceneLoader._getPluginForFilename = function (sceneFilename) {
-            var dotPosition = sceneFilename.lastIndexOf(".");
-            var queryStringPosition = sceneFilename.indexOf("?");
-            if (queryStringPosition === -1) {
-                queryStringPosition = sceneFilename.length;
-            }
-            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
-            for (var index = 0; index < this._registeredPlugins.length; index++) {
-                var plugin = this._registeredPlugins[index];
-                if (plugin.extensions.indexOf(extension) !== -1) {
-                    return plugin;
-                }
-            }
-            return this._registeredPlugins[0];
-        };
-        // Public functions
-        SceneLoader.GetPluginForExtension = function (extension) {
-            for (var index = 0; index < this._registeredPlugins.length; index++) {
-                var plugin = this._registeredPlugins[index];
-                if (plugin.extensions.indexOf(extension) !== -1) {
-                    return plugin;
-                }
-            }
-            return null;
-        };
-        SceneLoader.RegisterPlugin = function (plugin) {
-            plugin.extensions = plugin.extensions.toLowerCase();
-            SceneLoader._registeredPlugins.push(plugin);
-        };
-        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            var manifestChecked = function (success) {
-                scene.database = database;
-                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
-                var importMeshFromData = function (data) {
-                    var meshes = [];
-                    var particleSystems = [];
-                    var skeletons = [];
-                    try {
-                        if (plugin.importMesh) {
-                            var syncedPlugin = plugin;
-                            if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
-                                if (onerror) {
-                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
-                                }
-                                scene._removePendingData(loadingToken);
-                                return;
-                            }
-                            if (onsuccess) {
-                                scene.importedMeshesFiles.push(rootUrl + sceneFilename);
-                                onsuccess(meshes, particleSystems, skeletons);
-                                scene._removePendingData(loadingToken);
-                            }
-                        }
-                        else {
-                            var asyncedPlugin = plugin;
-                            asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
-                                if (onsuccess) {
-                                    scene.importedMeshesFiles.push(rootUrl + sceneFilename);
-                                    onsuccess(meshes, particleSystems, skeletons);
-                                    scene._removePendingData(loadingToken);
-                                }
-                            }, function () {
-                                if (onerror) {
-                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
-                                }
-                                scene._removePendingData(loadingToken);
-                            });
-                        }
-                    }
-                    catch (e) {
-                        if (onerror) {
-                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
-                        }
-                        scene._removePendingData(loadingToken);
-                    }
-                };
-                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                    // Direct load
-                    importMeshFromData(sceneFilename.substr(5));
-                    return;
-                }
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
-                    importMeshFromData(data);
-                }, progressCallBack, database);
-            };
-            if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
-                // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-            }
-            else {
-                // If the scene is a data stream or offline support is not enabled, it's a direct load
-                manifestChecked(true);
-            }
-        };
-        /**
-        * 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
-        */
-        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
-            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
-        };
-        /**
-        * 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
-        */
-        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
-            var database;
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            if (SceneLoader.ShowLoadingScreen) {
-                scene.getEngine().displayLoadingUI();
-            }
-            var loadSceneFromData = function (data) {
-                scene.database = database;
-                if (plugin.load) {
-                    var syncedPlugin = plugin;
-                    if (!syncedPlugin.load(scene, data, rootUrl)) {
-                        if (onerror) {
-                            onerror(scene);
-                        }
-                        scene._removePendingData(loadingToken);
-                        scene.getEngine().hideLoadingUI();
-                        return;
-                    }
-                    if (onsuccess) {
-                        onsuccess(scene);
-                    }
-                    scene._removePendingData(loadingToken);
-                }
-                else {
-                    var asyncedPlugin = plugin;
-                    asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
-                        if (onsuccess) {
-                            onsuccess(scene);
-                        }
-                    }, function () {
-                        if (onerror) {
-                            onerror(scene);
-                        }
-                        scene._removePendingData(loadingToken);
-                        scene.getEngine().hideLoadingUI();
-                    });
-                }
-                if (SceneLoader.ShowLoadingScreen) {
-                    scene.executeWhenReady(function () {
-                        scene.getEngine().hideLoadingUI();
-                    });
-                }
-            };
-            var manifestChecked = function (success) {
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
-            };
-            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                // Direct load
-                loadSceneFromData(sceneFilename.substr(5));
-                return;
-            }
-            if (rootUrl.indexOf("file:") === -1) {
-                if (scene.getEngine().enableOfflineSupport) {
-                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-                }
-                else {
-                    manifestChecked(true);
-                }
-            }
-            else {
-                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
-            }
-        };
-        // Flags
-        SceneLoader._ForceFullSceneLoadingForIncremental = false;
-        SceneLoader._ShowLoadingScreen = true;
-        SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
-        // Members
-        SceneLoader._registeredPlugins = new Array();
-        return SceneLoader;
-    }());
-    BABYLON.SceneLoader = SceneLoader;
-    ;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.sceneLoader.js.map
+var BABYLON;
+(function (BABYLON) {
+    var SceneLoader = (function () {
+        function SceneLoader() {
+        }
+        Object.defineProperty(SceneLoader, "NO_LOGGING", {
+            get: function () {
+                return 0;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
+            get: function () {
+                return 1;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
+            get: function () {
+                return 2;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
+            get: function () {
+                return 3;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
+            get: function () {
+                return SceneLoader._ForceFullSceneLoadingForIncremental;
+            },
+            set: function (value) {
+                SceneLoader._ForceFullSceneLoadingForIncremental = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
+            get: function () {
+                return SceneLoader._ShowLoadingScreen;
+            },
+            set: function (value) {
+                SceneLoader._ShowLoadingScreen = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "loggingLevel", {
+            get: function () {
+                return SceneLoader._loggingLevel;
+            },
+            set: function (value) {
+                SceneLoader._loggingLevel = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SceneLoader._getPluginForFilename = function (sceneFilename) {
+            var dotPosition = sceneFilename.lastIndexOf(".");
+            var queryStringPosition = sceneFilename.indexOf("?");
+            if (queryStringPosition === -1) {
+                queryStringPosition = sceneFilename.length;
+            }
+            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
+            for (var index = 0; index < this._registeredPlugins.length; index++) {
+                var plugin = this._registeredPlugins[index];
+                if (plugin.extensions.indexOf(extension) !== -1) {
+                    return plugin;
+                }
+            }
+            return this._registeredPlugins[0];
+        };
+        // Public functions
+        SceneLoader.GetPluginForExtension = function (extension) {
+            for (var index = 0; index < this._registeredPlugins.length; index++) {
+                var plugin = this._registeredPlugins[index];
+                if (plugin.extensions.indexOf(extension) !== -1) {
+                    return plugin;
+                }
+            }
+            return null;
+        };
+        SceneLoader.RegisterPlugin = function (plugin) {
+            plugin.extensions = plugin.extensions.toLowerCase();
+            SceneLoader._registeredPlugins.push(plugin);
+        };
+        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            var manifestChecked = function (success) {
+                scene.database = database;
+                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
+                var importMeshFromData = function (data) {
+                    var meshes = [];
+                    var particleSystems = [];
+                    var skeletons = [];
+                    try {
+                        if (plugin.importMesh) {
+                            var syncedPlugin = plugin;
+                            if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
+                                if (onerror) {
+                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
+                                }
+                                scene._removePendingData(loadingToken);
+                                return;
+                            }
+                            if (onsuccess) {
+                                scene.importedMeshesFiles.push(rootUrl + sceneFilename);
+                                onsuccess(meshes, particleSystems, skeletons);
+                                scene._removePendingData(loadingToken);
+                            }
+                        }
+                        else {
+                            var asyncedPlugin = plugin;
+                            asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
+                                if (onsuccess) {
+                                    scene.importedMeshesFiles.push(rootUrl + sceneFilename);
+                                    onsuccess(meshes, particleSystems, skeletons);
+                                    scene._removePendingData(loadingToken);
+                                }
+                            }, function () {
+                                if (onerror) {
+                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
+                                }
+                                scene._removePendingData(loadingToken);
+                            });
+                        }
+                    }
+                    catch (e) {
+                        if (onerror) {
+                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
+                        }
+                        scene._removePendingData(loadingToken);
+                    }
+                };
+                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                    // Direct load
+                    importMeshFromData(sceneFilename.substr(5));
+                    return;
+                }
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
+                    importMeshFromData(data);
+                }, progressCallBack, database);
+            };
+            if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
+                // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+            }
+            else {
+                // If the scene is a data stream or offline support is not enabled, it's a direct load
+                manifestChecked(true);
+            }
+        };
+        /**
+        * 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
+        */
+        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
+            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
+        };
+        /**
+        * 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
+        */
+        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
+            var database;
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            if (SceneLoader.ShowLoadingScreen) {
+                scene.getEngine().displayLoadingUI();
+            }
+            var loadSceneFromData = function (data) {
+                scene.database = database;
+                if (plugin.load) {
+                    var syncedPlugin = plugin;
+                    if (!syncedPlugin.load(scene, data, rootUrl)) {
+                        if (onerror) {
+                            onerror(scene);
+                        }
+                        scene._removePendingData(loadingToken);
+                        scene.getEngine().hideLoadingUI();
+                        return;
+                    }
+                    if (onsuccess) {
+                        onsuccess(scene);
+                    }
+                    scene._removePendingData(loadingToken);
+                }
+                else {
+                    var asyncedPlugin = plugin;
+                    asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
+                        if (onsuccess) {
+                            onsuccess(scene);
+                        }
+                    }, function () {
+                        if (onerror) {
+                            onerror(scene);
+                        }
+                        scene._removePendingData(loadingToken);
+                        scene.getEngine().hideLoadingUI();
+                    });
+                }
+                if (SceneLoader.ShowLoadingScreen) {
+                    scene.executeWhenReady(function () {
+                        scene.getEngine().hideLoadingUI();
+                    });
+                }
+            };
+            var manifestChecked = function (success) {
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
+            };
+            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                // Direct load
+                loadSceneFromData(sceneFilename.substr(5));
+                return;
+            }
+            if (rootUrl.indexOf("file:") === -1) {
+                if (scene.getEngine().enableOfflineSupport) {
+                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+                }
+                else {
+                    manifestChecked(true);
+                }
+            }
+            else {
+                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
+            }
+        };
+        // Flags
+        SceneLoader._ForceFullSceneLoadingForIncremental = false;
+        SceneLoader._ShowLoadingScreen = true;
+        SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
+        // Members
+        SceneLoader._registeredPlugins = new Array();
+        return SceneLoader;
+    })();
+    BABYLON.SceneLoader = SceneLoader;
+    ;
+})(BABYLON || (BABYLON = {}));

+ 124 - 125
src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js

@@ -1,125 +1,124 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var CustomProceduralTexture = (function (_super) {
-        __extends(CustomProceduralTexture, _super);
-        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
-            _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
-            this._animate = true;
-            this._time = 0;
-            this._texturePath = texturePath;
-            //Try to load json
-            this.loadJson(texturePath);
-            this.refreshRate = 1;
-        }
-        CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
-            var _this = this;
-            var that = this;
-            function noConfigFile() {
-                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
-                try {
-                    that.setFragment(that._texturePath);
-                }
-                catch (ex) {
-                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
-                }
-            }
-            var configFileUrl = jsonUrl + "/config.json";
-            var xhr = new XMLHttpRequest();
-            xhr.open("GET", configFileUrl, true);
-            xhr.addEventListener("load", function () {
-                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
-                    try {
-                        _this._config = JSON.parse(xhr.response);
-                        _this.updateShaderUniforms();
-                        _this.updateTextures();
-                        _this.setFragment(_this._texturePath + "/custom");
-                        _this._animate = _this._config.animate;
-                        _this.refreshRate = _this._config.refreshrate;
-                    }
-                    catch (ex) {
-                        noConfigFile();
-                    }
-                }
-                else {
-                    noConfigFile();
-                }
-            }, false);
-            xhr.addEventListener("error", function () {
-                noConfigFile();
-            }, false);
-            try {
-                xhr.send();
-            }
-            catch (ex) {
-                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
-            }
-        };
-        CustomProceduralTexture.prototype.isReady = function () {
-            if (!_super.prototype.isReady.call(this)) {
-                return false;
-            }
-            for (var name in this._textures) {
-                var texture = this._textures[name];
-                if (!texture.isReady()) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
-            if (this._animate) {
-                this._time += this.getScene().getAnimationRatio() * 0.03;
-                this.updateShaderUniforms();
-            }
-            _super.prototype.render.call(this, useCameraPostProcess);
-        };
-        CustomProceduralTexture.prototype.updateTextures = function () {
-            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
-                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
-            }
-        };
-        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
-            if (this._config) {
-                for (var j = 0; j < this._config.uniforms.length; j++) {
-                    var uniform = this._config.uniforms[j];
-                    switch (uniform.type) {
-                        case "float":
-                            this.setFloat(uniform.name, uniform.value);
-                            break;
-                        case "color3":
-                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
-                            break;
-                        case "color4":
-                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
-                            break;
-                        case "vector2":
-                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
-                            break;
-                        case "vector3":
-                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
-                            break;
-                    }
-                }
-            }
-            this.setFloat("time", this._time);
-        };
-        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
-            get: function () {
-                return this._animate;
-            },
-            set: function (value) {
-                this._animate = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        return CustomProceduralTexture;
-    }(BABYLON.ProceduralTexture));
-    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.customProceduralTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var CustomProceduralTexture = (function (_super) {
+        __extends(CustomProceduralTexture, _super);
+        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
+            _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
+            this._animate = true;
+            this._time = 0;
+            this._texturePath = texturePath;
+            //Try to load json
+            this.loadJson(texturePath);
+            this.refreshRate = 1;
+        }
+        CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
+            var _this = this;
+            var that = this;
+            function noConfigFile() {
+                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
+                try {
+                    that.setFragment(that._texturePath);
+                }
+                catch (ex) {
+                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
+                }
+            }
+            var configFileUrl = jsonUrl + "/config.json";
+            var xhr = new XMLHttpRequest();
+            xhr.open("GET", configFileUrl, true);
+            xhr.addEventListener("load", function () {
+                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
+                    try {
+                        _this._config = JSON.parse(xhr.response);
+                        _this.updateShaderUniforms();
+                        _this.updateTextures();
+                        _this.setFragment(_this._texturePath + "/custom");
+                        _this._animate = _this._config.animate;
+                        _this.refreshRate = _this._config.refreshrate;
+                    }
+                    catch (ex) {
+                        noConfigFile();
+                    }
+                }
+                else {
+                    noConfigFile();
+                }
+            }, false);
+            xhr.addEventListener("error", function () {
+                noConfigFile();
+            }, false);
+            try {
+                xhr.send();
+            }
+            catch (ex) {
+                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
+            }
+        };
+        CustomProceduralTexture.prototype.isReady = function () {
+            if (!_super.prototype.isReady.call(this)) {
+                return false;
+            }
+            for (var name in this._textures) {
+                var texture = this._textures[name];
+                if (!texture.isReady()) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
+            if (this._animate) {
+                this._time += this.getScene().getAnimationRatio() * 0.03;
+                this.updateShaderUniforms();
+            }
+            _super.prototype.render.call(this, useCameraPostProcess);
+        };
+        CustomProceduralTexture.prototype.updateTextures = function () {
+            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
+                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
+            }
+        };
+        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
+            if (this._config) {
+                for (var j = 0; j < this._config.uniforms.length; j++) {
+                    var uniform = this._config.uniforms[j];
+                    switch (uniform.type) {
+                        case "float":
+                            this.setFloat(uniform.name, uniform.value);
+                            break;
+                        case "color3":
+                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
+                            break;
+                        case "color4":
+                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
+                            break;
+                        case "vector2":
+                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
+                            break;
+                        case "vector3":
+                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
+                            break;
+                    }
+                }
+            }
+            this.setFloat("time", this._time);
+        };
+        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
+            get: function () {
+                return this._animate;
+            },
+            set: function (value) {
+                this._animate = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        return CustomProceduralTexture;
+    })(BABYLON.ProceduralTexture);
+    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
+})(BABYLON || (BABYLON = {}));

+ 284 - 285
src/Materials/Textures/Procedurals/babylon.proceduralTexture.js

@@ -1,285 +1,284 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var ProceduralTexture = (function (_super) {
-        __extends(ProceduralTexture, _super);
-        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (isCube === void 0) { isCube = false; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.isCube = isCube;
-            this.isEnabled = true;
-            this._currentRefreshId = -1;
-            this._refreshRate = 1;
-            this._vertexBuffers = {};
-            this._uniforms = new Array();
-            this._samplers = new Array();
-            this._textures = new Array();
-            this._floats = new Array();
-            this._floatsArrays = {};
-            this._colors3 = new Array();
-            this._colors4 = new Array();
-            this._vectors2 = new Array();
-            this._vectors3 = new Array();
-            this._matrices = new Array();
-            this._fallbackTextureUsed = false;
-            scene._proceduralTextures.push(this);
-            this.name = name;
-            this.isRenderTarget = true;
-            this._size = size;
-            this._generateMipMaps = generateMipMaps;
-            this.setFragment(fragment);
-            this._fallbackTexture = fallbackTexture;
-            var engine = scene.getEngine();
-            if (isCube) {
-                this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
-                this.setFloat("face", 0);
-            }
-            else {
-                this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
-            }
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = engine.createIndexBuffer(indices);
-        }
-        ProceduralTexture.prototype.reset = function () {
-            if (this._effect === undefined) {
-                return;
-            }
-            var engine = this.getScene().getEngine();
-            engine._releaseEffect(this._effect);
-        };
-        ProceduralTexture.prototype.isReady = function () {
-            var _this = this;
-            var engine = this.getScene().getEngine();
-            var shaders;
-            if (!this._fragment) {
-                return false;
-            }
-            if (this._fallbackTextureUsed) {
-                return true;
-            }
-            if (this._fragment.fragmentElement !== undefined) {
-                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
-            }
-            else {
-                shaders = { vertex: "procedural", fragment: this._fragment };
-            }
-            this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
-                _this.releaseInternalTexture();
-                if (_this._fallbackTexture) {
-                    _this._texture = _this._fallbackTexture._texture;
-                    _this._texture.references++;
-                }
-                _this._fallbackTextureUsed = true;
-            });
-            return this._effect.isReady();
-        };
-        ProceduralTexture.prototype.resetRefreshCounter = function () {
-            this._currentRefreshId = -1;
-        };
-        ProceduralTexture.prototype.setFragment = function (fragment) {
-            this._fragment = fragment;
-        };
-        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
-            get: function () {
-                return this._refreshRate;
-            },
-            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
-            set: function (value) {
-                this._refreshRate = value;
-                this.resetRefreshCounter();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ProceduralTexture.prototype._shouldRender = function () {
-            if (!this.isEnabled || !this.isReady() || !this._texture) {
-                return false;
-            }
-            if (this._fallbackTextureUsed) {
-                return false;
-            }
-            if (this._currentRefreshId === -1) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            if (this.refreshRate === this._currentRefreshId) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            this._currentRefreshId++;
-            return false;
-        };
-        ProceduralTexture.prototype.getRenderSize = function () {
-            return this._size;
-        };
-        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
-            if (this._fallbackTextureUsed) {
-                return;
-            }
-            this.releaseInternalTexture();
-            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
-        };
-        ProceduralTexture.prototype._checkUniform = function (uniformName) {
-            if (this._uniforms.indexOf(uniformName) === -1) {
-                this._uniforms.push(uniformName);
-            }
-        };
-        ProceduralTexture.prototype.setTexture = function (name, texture) {
-            if (this._samplers.indexOf(name) === -1) {
-                this._samplers.push(name);
-            }
-            this._textures[name] = texture;
-            return this;
-        };
-        ProceduralTexture.prototype.setFloat = function (name, value) {
-            this._checkUniform(name);
-            this._floats[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setFloats = function (name, value) {
-            this._checkUniform(name);
-            this._floatsArrays[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setColor3 = function (name, value) {
-            this._checkUniform(name);
-            this._colors3[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setColor4 = function (name, value) {
-            this._checkUniform(name);
-            this._colors4[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setVector2 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors2[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setVector3 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors3[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setMatrix = function (name, value) {
-            this._checkUniform(name);
-            this._matrices[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            // Render
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            // Texture
-            for (var name in this._textures) {
-                this._effect.setTexture(name, this._textures[name]);
-            }
-            // Float    
-            for (name in this._floats) {
-                this._effect.setFloat(name, this._floats[name]);
-            }
-            // Floats   
-            for (name in this._floatsArrays) {
-                this._effect.setArray(name, this._floatsArrays[name]);
-            }
-            // Color3        
-            for (name in this._colors3) {
-                this._effect.setColor3(name, this._colors3[name]);
-            }
-            // Color4      
-            for (name in this._colors4) {
-                var color = this._colors4[name];
-                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
-            }
-            // Vector2        
-            for (name in this._vectors2) {
-                this._effect.setVector2(name, this._vectors2[name]);
-            }
-            // Vector3        
-            for (name in this._vectors3) {
-                this._effect.setVector3(name, this._vectors3[name]);
-            }
-            // Matrix      
-            for (name in this._matrices) {
-                this._effect.setMatrix(name, this._matrices[name]);
-            }
-            // VBOs
-            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
-            if (this.isCube) {
-                for (var face = 0; face < 6; face++) {
-                    engine.bindFramebuffer(this._texture, face);
-                    this._effect.setFloat("face", face);
-                    // Clear
-                    engine.clear(scene.clearColor, true, true);
-                    // Draw order
-                    engine.draw(true, 0, 6);
-                    // Mipmaps
-                    if (face === 5) {
-                        engine.generateMipMapsForCubemap(this._texture);
-                    }
-                }
-            }
-            else {
-                engine.bindFramebuffer(this._texture);
-                // Clear
-                engine.clear(scene.clearColor, true, true);
-                // Draw order
-                engine.draw(true, 0, 6);
-            }
-            // Unbind
-            engine.unBindFramebuffer(this._texture, this.isCube);
-            if (this.onGenerated) {
-                this.onGenerated();
-            }
-        };
-        ProceduralTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // RenderTarget Texture
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        ProceduralTexture.prototype.dispose = function () {
-            var index = this.getScene()._proceduralTextures.indexOf(this);
-            if (index >= 0) {
-                this.getScene()._proceduralTextures.splice(index, 1);
-            }
-            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
-            if (vertexBuffer) {
-                vertexBuffer.dispose();
-                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
-            }
-            if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
-                this._indexBuffer = null;
-            }
-            _super.prototype.dispose.call(this);
-        };
-        return ProceduralTexture;
-    }(BABYLON.Texture));
-    BABYLON.ProceduralTexture = ProceduralTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.proceduralTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var ProceduralTexture = (function (_super) {
+        __extends(ProceduralTexture, _super);
+        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (isCube === void 0) { isCube = false; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.isCube = isCube;
+            this.isEnabled = true;
+            this._currentRefreshId = -1;
+            this._refreshRate = 1;
+            this._vertexBuffers = {};
+            this._uniforms = new Array();
+            this._samplers = new Array();
+            this._textures = new Array();
+            this._floats = new Array();
+            this._floatsArrays = {};
+            this._colors3 = new Array();
+            this._colors4 = new Array();
+            this._vectors2 = new Array();
+            this._vectors3 = new Array();
+            this._matrices = new Array();
+            this._fallbackTextureUsed = false;
+            scene._proceduralTextures.push(this);
+            this.name = name;
+            this.isRenderTarget = true;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+            this.setFragment(fragment);
+            this._fallbackTexture = fallbackTexture;
+            var engine = scene.getEngine();
+            if (isCube) {
+                this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
+                this.setFloat("face", 0);
+            }
+            else {
+                this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
+            }
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = engine.createIndexBuffer(indices);
+        }
+        ProceduralTexture.prototype.reset = function () {
+            if (this._effect === undefined) {
+                return;
+            }
+            var engine = this.getScene().getEngine();
+            engine._releaseEffect(this._effect);
+        };
+        ProceduralTexture.prototype.isReady = function () {
+            var _this = this;
+            var engine = this.getScene().getEngine();
+            var shaders;
+            if (!this._fragment) {
+                return false;
+            }
+            if (this._fallbackTextureUsed) {
+                return true;
+            }
+            if (this._fragment.fragmentElement !== undefined) {
+                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
+            }
+            else {
+                shaders = { vertex: "procedural", fragment: this._fragment };
+            }
+            this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
+                _this.releaseInternalTexture();
+                if (_this._fallbackTexture) {
+                    _this._texture = _this._fallbackTexture._texture;
+                    _this._texture.references++;
+                }
+                _this._fallbackTextureUsed = true;
+            });
+            return this._effect.isReady();
+        };
+        ProceduralTexture.prototype.resetRefreshCounter = function () {
+            this._currentRefreshId = -1;
+        };
+        ProceduralTexture.prototype.setFragment = function (fragment) {
+            this._fragment = fragment;
+        };
+        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
+            get: function () {
+                return this._refreshRate;
+            },
+            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+            set: function (value) {
+                this._refreshRate = value;
+                this.resetRefreshCounter();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ProceduralTexture.prototype._shouldRender = function () {
+            if (!this.isEnabled || !this.isReady() || !this._texture) {
+                return false;
+            }
+            if (this._fallbackTextureUsed) {
+                return false;
+            }
+            if (this._currentRefreshId === -1) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            if (this.refreshRate === this._currentRefreshId) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            this._currentRefreshId++;
+            return false;
+        };
+        ProceduralTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
+            if (this._fallbackTextureUsed) {
+                return;
+            }
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+        };
+        ProceduralTexture.prototype._checkUniform = function (uniformName) {
+            if (this._uniforms.indexOf(uniformName) === -1) {
+                this._uniforms.push(uniformName);
+            }
+        };
+        ProceduralTexture.prototype.setTexture = function (name, texture) {
+            if (this._samplers.indexOf(name) === -1) {
+                this._samplers.push(name);
+            }
+            this._textures[name] = texture;
+            return this;
+        };
+        ProceduralTexture.prototype.setFloat = function (name, value) {
+            this._checkUniform(name);
+            this._floats[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setFloats = function (name, value) {
+            this._checkUniform(name);
+            this._floatsArrays[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setColor3 = function (name, value) {
+            this._checkUniform(name);
+            this._colors3[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setColor4 = function (name, value) {
+            this._checkUniform(name);
+            this._colors4[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setVector2 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors2[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setVector3 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors3[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setMatrix = function (name, value) {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            // Render
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            // Texture
+            for (var name in this._textures) {
+                this._effect.setTexture(name, this._textures[name]);
+            }
+            // Float    
+            for (name in this._floats) {
+                this._effect.setFloat(name, this._floats[name]);
+            }
+            // Floats   
+            for (name in this._floatsArrays) {
+                this._effect.setArray(name, this._floatsArrays[name]);
+            }
+            // Color3        
+            for (name in this._colors3) {
+                this._effect.setColor3(name, this._colors3[name]);
+            }
+            // Color4      
+            for (name in this._colors4) {
+                var color = this._colors4[name];
+                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
+            }
+            // Vector2        
+            for (name in this._vectors2) {
+                this._effect.setVector2(name, this._vectors2[name]);
+            }
+            // Vector3        
+            for (name in this._vectors3) {
+                this._effect.setVector3(name, this._vectors3[name]);
+            }
+            // Matrix      
+            for (name in this._matrices) {
+                this._effect.setMatrix(name, this._matrices[name]);
+            }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
+            if (this.isCube) {
+                for (var face = 0; face < 6; face++) {
+                    engine.bindFramebuffer(this._texture, face);
+                    this._effect.setFloat("face", face);
+                    // Clear
+                    engine.clear(scene.clearColor, true, true);
+                    // Draw order
+                    engine.draw(true, 0, 6);
+                    // Mipmaps
+                    if (face === 5) {
+                        engine.generateMipMapsForCubemap(this._texture);
+                    }
+                }
+            }
+            else {
+                engine.bindFramebuffer(this._texture);
+                // Clear
+                engine.clear(scene.clearColor, true, true);
+                // Draw order
+                engine.draw(true, 0, 6);
+            }
+            // Unbind
+            engine.unBindFramebuffer(this._texture, this.isCube);
+            if (this.onGenerated) {
+                this.onGenerated();
+            }
+        };
+        ProceduralTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // RenderTarget Texture
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        ProceduralTexture.prototype.dispose = function () {
+            var index = this.getScene()._proceduralTextures.indexOf(this);
+            if (index >= 0) {
+                this.getScene()._proceduralTextures.splice(index, 1);
+            }
+            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
+            if (vertexBuffer) {
+                vertexBuffer.dispose();
+                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
+            }
+            if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
+                this._indexBuffer = null;
+            }
+            _super.prototype.dispose.call(this);
+        };
+        return ProceduralTexture;
+    })(BABYLON.Texture);
+    BABYLON.ProceduralTexture = ProceduralTexture;
+})(BABYLON || (BABYLON = {}));

+ 187 - 188
src/Materials/Textures/babylon.baseTexture.js

@@ -1,188 +1,187 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var BaseTexture = (function () {
-        function BaseTexture(scene) {
-            this.hasAlpha = false;
-            this.getAlphaFromRGB = false;
-            this.level = 1;
-            this.coordinatesIndex = 0;
-            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
-            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.anisotropicFilteringLevel = 4;
-            this.isCube = false;
-            this.isRenderTarget = false;
-            this.animations = new Array();
-            /**
-            * An event triggered when the texture is disposed.
-            * @type {BABYLON.Observable}
-            */
-            this.onDisposeObservable = new BABYLON.Observable();
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
-            this._scene = scene;
-            this._scene.textures.push(this);
-        }
-        BaseTexture.prototype.toString = function () {
-            return this.name;
-        };
-        Object.defineProperty(BaseTexture.prototype, "onDispose", {
-            set: function (callback) {
-                if (this._onDisposeObserver) {
-                    this.onDisposeObservable.remove(this._onDisposeObserver);
-                }
-                this._onDisposeObserver = this.onDisposeObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        BaseTexture.prototype.getScene = function () {
-            return this._scene;
-        };
-        BaseTexture.prototype.getTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getReflectionTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getInternalTexture = function () {
-            return this._texture;
-        };
-        BaseTexture.prototype.isReady = function () {
-            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return true;
-            }
-            if (this._texture) {
-                return this._texture.isReady;
-            }
-            return false;
-        };
-        BaseTexture.prototype.getSize = function () {
-            if (this._texture._width) {
-                return { width: this._texture._width, height: this._texture._height };
-            }
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: 0, height: 0 };
-        };
-        BaseTexture.prototype.getBaseSize = function () {
-            if (!this.isReady() || !this._texture)
-                return { width: 0, height: 0 };
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
-        };
-        BaseTexture.prototype.scale = function (ratio) {
-        };
-        Object.defineProperty(BaseTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    texturesCache.splice(index, 1);
-                    return;
-                }
-            }
-        };
-        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
-                        texturesCacheEntry.references++;
-                        return texturesCacheEntry;
-                    }
-                }
-            }
-            return null;
-        };
-        BaseTexture.prototype.delayLoad = function () {
-        };
-        BaseTexture.prototype.clone = function () {
-            return null;
-        };
-        BaseTexture.prototype.releaseInternalTexture = function () {
-            if (this._texture) {
-                this._scene.getEngine().releaseInternalTexture(this._texture);
-                delete this._texture;
-            }
-        };
-        BaseTexture.prototype.dispose = function () {
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            var index = this._scene.textures.indexOf(this);
-            if (index >= 0) {
-                this._scene.textures.splice(index, 1);
-            }
-            if (this._texture === undefined) {
-                return;
-            }
-            // Release
-            this.releaseInternalTexture();
-            // Callback
-            this.onDisposeObservable.notifyObservers(this);
-            this.onDisposeObservable.clear();
-        };
-        BaseTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
-            // Animations
-            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
-            return serializationObject;
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "name", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "hasAlpha", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "level", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "coordinatesIndex", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "coordinatesMode", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "wrapU", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "wrapV", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "isCube", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], BaseTexture.prototype, "isRenderTarget", void 0);
-        return BaseTexture;
-    }());
-    BABYLON.BaseTexture = BaseTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.baseTexture.js.map
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var BaseTexture = (function () {
+        function BaseTexture(scene) {
+            this.hasAlpha = false;
+            this.getAlphaFromRGB = false;
+            this.level = 1;
+            this.coordinatesIndex = 0;
+            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
+            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.anisotropicFilteringLevel = 4;
+            this.isCube = false;
+            this.isRenderTarget = false;
+            this.animations = new Array();
+            /**
+            * An event triggered when the texture is disposed.
+            * @type {BABYLON.Observable}
+            */
+            this.onDisposeObservable = new BABYLON.Observable();
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
+            this._scene = scene;
+            this._scene.textures.push(this);
+        }
+        BaseTexture.prototype.toString = function () {
+            return this.name;
+        };
+        Object.defineProperty(BaseTexture.prototype, "onDispose", {
+            set: function (callback) {
+                if (this._onDisposeObserver) {
+                    this.onDisposeObservable.remove(this._onDisposeObserver);
+                }
+                this._onDisposeObserver = this.onDisposeObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        BaseTexture.prototype.getScene = function () {
+            return this._scene;
+        };
+        BaseTexture.prototype.getTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getReflectionTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getInternalTexture = function () {
+            return this._texture;
+        };
+        BaseTexture.prototype.isReady = function () {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return true;
+            }
+            if (this._texture) {
+                return this._texture.isReady;
+            }
+            return false;
+        };
+        BaseTexture.prototype.getSize = function () {
+            if (this._texture._width) {
+                return { width: this._texture._width, height: this._texture._height };
+            }
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: 0, height: 0 };
+        };
+        BaseTexture.prototype.getBaseSize = function () {
+            if (!this.isReady() || !this._texture)
+                return { width: 0, height: 0 };
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
+        };
+        BaseTexture.prototype.scale = function (ratio) {
+        };
+        Object.defineProperty(BaseTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    texturesCache.splice(index, 1);
+                    return;
+                }
+            }
+        };
+        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
+                        texturesCacheEntry.references++;
+                        return texturesCacheEntry;
+                    }
+                }
+            }
+            return null;
+        };
+        BaseTexture.prototype.delayLoad = function () {
+        };
+        BaseTexture.prototype.clone = function () {
+            return null;
+        };
+        BaseTexture.prototype.releaseInternalTexture = function () {
+            if (this._texture) {
+                this._scene.getEngine().releaseInternalTexture(this._texture);
+                delete this._texture;
+            }
+        };
+        BaseTexture.prototype.dispose = function () {
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            var index = this._scene.textures.indexOf(this);
+            if (index >= 0) {
+                this._scene.textures.splice(index, 1);
+            }
+            if (this._texture === undefined) {
+                return;
+            }
+            // Release
+            this.releaseInternalTexture();
+            // Callback
+            this.onDisposeObservable.notifyObservers(this);
+            this.onDisposeObservable.clear();
+        };
+        BaseTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
+            // Animations
+            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
+            return serializationObject;
+        };
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "name", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "hasAlpha", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "level", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "coordinatesIndex", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "coordinatesMode", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "wrapU", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "wrapV", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "isCube", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], BaseTexture.prototype, "isRenderTarget", void 0);
+        return BaseTexture;
+    })();
+    BABYLON.BaseTexture = BaseTexture;
+})(BABYLON || (BABYLON = {}));

+ 182 - 183
src/Materials/Textures/babylon.colorGradingTexture.js

@@ -1,183 +1,182 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
-     * It can help converting any input color in a desired output one. This can then be used to create effects
-     * from sepia, black and white to sixties or futuristic rendering...
-     *
-     * The only supported format is currently 3dl.
-     * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
-     */
-    var ColorGradingTexture = (function (_super) {
-        __extends(ColorGradingTexture, _super);
-        /**
-         * Instantiates a ColorGradingTexture from the following parameters.
-         *
-         * @param url The location of the color gradind data (currently only supporting 3dl)
-         * @param scene The scene the texture will be used in
-         */
-        function ColorGradingTexture(url, scene) {
-            _super.call(this, scene);
-            if (!url) {
-                return;
-            }
-            this._textureMatrix = BABYLON.Matrix.Identity();
-            this.name = url;
-            this.url = url;
-            this.hasAlpha = false;
-            this.isCube = false;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.anisotropicFilteringLevel = 1;
-            this._texture = this._getFromCache(url, true);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this.loadTexture();
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-        }
-        /**
-         * Returns the texture matrix used in most of the material.
-         * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
-         */
-        ColorGradingTexture.prototype.getTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        /**
-         * Occurs when the file being loaded is a .3dl LUT file.
-         */
-        ColorGradingTexture.prototype.load3dlTexture = function () {
-            var _this = this;
-            var mipLevels = 0;
-            var floatArrayView = null;
-            var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
-            this._texture = texture;
-            var callback = function (text) {
-                var data;
-                var tempData;
-                var line;
-                var lines = text.split('\n');
-                var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
-                var maxColor = 0;
-                for (var i = 0; i < lines.length; i++) {
-                    line = lines[i];
-                    if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
-                        continue;
-                    if (line.indexOf('#') === 0)
-                        continue;
-                    var words = line.split(" ");
-                    if (size === 0) {
-                        // Number of space + one
-                        size = words.length;
-                        data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
-                        tempData = new Float32Array(size * size * size * 4);
-                        continue;
-                    }
-                    if (size != 0) {
-                        var r = Math.max(parseInt(words[0]), 0);
-                        var g = Math.max(parseInt(words[1]), 0);
-                        var b = Math.max(parseInt(words[2]), 0);
-                        maxColor = Math.max(r, maxColor);
-                        maxColor = Math.max(g, maxColor);
-                        maxColor = Math.max(b, maxColor);
-                        var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
-                        tempData[pixelStorageIndex + 0] = r;
-                        tempData[pixelStorageIndex + 1] = g;
-                        tempData[pixelStorageIndex + 2] = b;
-                        tempData[pixelStorageIndex + 3] = 0;
-                        pixelIndexSlice++;
-                        if (pixelIndexSlice % size == 0) {
-                            pixelIndexH++;
-                            pixelIndexSlice = 0;
-                            if (pixelIndexH % size == 0) {
-                                pixelIndexW++;
-                                pixelIndexH = 0;
-                            }
-                        }
-                    }
-                }
-                for (var i = 0; i < tempData.length; i++) {
-                    var value = tempData[i];
-                    data[i] = (value / maxColor * 255);
-                }
-                _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
-                _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
-            };
-            BABYLON.Tools.LoadFile(this.url, callback);
-            return this._texture;
-        };
-        /**
-         * Starts the loading process of the texture.
-         */
-        ColorGradingTexture.prototype.loadTexture = function () {
-            if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
-                this.load3dlTexture();
-            }
-        };
-        /**
-         * Clones the color gradind texture.
-         */
-        ColorGradingTexture.prototype.clone = function () {
-            var newTexture = new ColorGradingTexture(this.url, this.getScene());
-            // Base texture
-            newTexture.level = this.level;
-            return newTexture;
-        };
-        /**
-         * Called during delayed load for textures.
-         */
-        ColorGradingTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, true);
-            if (!this._texture) {
-                this.loadTexture();
-            }
-        };
-        /**
-         * Parses a color grading texture serialized by Babylon.
-         * @param parsedTexture The texture information being parsedTexture
-         * @param scene The scene to load the texture in
-         * @param rootUrl The root url of the data assets to load
-         * @return A color gradind texture
-         */
-        ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
-                texture.name = parsedTexture.name;
-                texture.level = parsedTexture.level;
-            }
-            return texture;
-        };
-        /**
-         * Serializes the LUT texture to json format.
-         */
-        ColorGradingTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.level = this.level;
-            return serializationObject;
-        };
-        /**
-         * Empty line regex stored for GC.
-         */
-        ColorGradingTexture._noneEmptyLineRegex = /\S+/;
-        return ColorGradingTexture;
-    }(BABYLON.BaseTexture));
-    BABYLON.ColorGradingTexture = ColorGradingTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.colorGradingTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
+     * It can help converting any input color in a desired output one. This can then be used to create effects
+     * from sepia, black and white to sixties or futuristic rendering...
+     *
+     * The only supported format is currently 3dl.
+     * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
+     */
+    var ColorGradingTexture = (function (_super) {
+        __extends(ColorGradingTexture, _super);
+        /**
+         * Instantiates a ColorGradingTexture from the following parameters.
+         *
+         * @param url The location of the color gradind data (currently only supporting 3dl)
+         * @param scene The scene the texture will be used in
+         */
+        function ColorGradingTexture(url, scene) {
+            _super.call(this, scene);
+            if (!url) {
+                return;
+            }
+            this._textureMatrix = BABYLON.Matrix.Identity();
+            this.name = url;
+            this.url = url;
+            this.hasAlpha = false;
+            this.isCube = false;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.anisotropicFilteringLevel = 1;
+            this._texture = this._getFromCache(url, true);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this.loadTexture();
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+        }
+        /**
+         * Returns the texture matrix used in most of the material.
+         * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
+         */
+        ColorGradingTexture.prototype.getTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        /**
+         * Occurs when the file being loaded is a .3dl LUT file.
+         */
+        ColorGradingTexture.prototype.load3dlTexture = function () {
+            var _this = this;
+            var mipLevels = 0;
+            var floatArrayView = null;
+            var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
+            this._texture = texture;
+            var callback = function (text) {
+                var data;
+                var tempData;
+                var line;
+                var lines = text.split('\n');
+                var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
+                var maxColor = 0;
+                for (var i = 0; i < lines.length; i++) {
+                    line = lines[i];
+                    if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
+                        continue;
+                    if (line.indexOf('#') === 0)
+                        continue;
+                    var words = line.split(" ");
+                    if (size === 0) {
+                        // Number of space + one
+                        size = words.length;
+                        data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
+                        tempData = new Float32Array(size * size * size * 4);
+                        continue;
+                    }
+                    if (size != 0) {
+                        var r = Math.max(parseInt(words[0]), 0);
+                        var g = Math.max(parseInt(words[1]), 0);
+                        var b = Math.max(parseInt(words[2]), 0);
+                        maxColor = Math.max(r, maxColor);
+                        maxColor = Math.max(g, maxColor);
+                        maxColor = Math.max(b, maxColor);
+                        var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
+                        tempData[pixelStorageIndex + 0] = r;
+                        tempData[pixelStorageIndex + 1] = g;
+                        tempData[pixelStorageIndex + 2] = b;
+                        tempData[pixelStorageIndex + 3] = 0;
+                        pixelIndexSlice++;
+                        if (pixelIndexSlice % size == 0) {
+                            pixelIndexH++;
+                            pixelIndexSlice = 0;
+                            if (pixelIndexH % size == 0) {
+                                pixelIndexW++;
+                                pixelIndexH = 0;
+                            }
+                        }
+                    }
+                }
+                for (var i = 0; i < tempData.length; i++) {
+                    var value = tempData[i];
+                    data[i] = (value / maxColor * 255);
+                }
+                _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
+                _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
+            };
+            BABYLON.Tools.LoadFile(this.url, callback);
+            return this._texture;
+        };
+        /**
+         * Starts the loading process of the texture.
+         */
+        ColorGradingTexture.prototype.loadTexture = function () {
+            if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
+                this.load3dlTexture();
+            }
+        };
+        /**
+         * Clones the color gradind texture.
+         */
+        ColorGradingTexture.prototype.clone = function () {
+            var newTexture = new ColorGradingTexture(this.url, this.getScene());
+            // Base texture
+            newTexture.level = this.level;
+            return newTexture;
+        };
+        /**
+         * Called during delayed load for textures.
+         */
+        ColorGradingTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, true);
+            if (!this._texture) {
+                this.loadTexture();
+            }
+        };
+        /**
+         * Parses a color grading texture serialized by Babylon.
+         * @param parsedTexture The texture information being parsedTexture
+         * @param scene The scene to load the texture in
+         * @param rootUrl The root url of the data assets to load
+         * @return A color gradind texture
+         */
+        ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
+                texture.name = parsedTexture.name;
+                texture.level = parsedTexture.level;
+            }
+            return texture;
+        };
+        /**
+         * Serializes the LUT texture to json format.
+         */
+        ColorGradingTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.level = this.level;
+            return serializationObject;
+        };
+        /**
+         * Empty line regex stored for GC.
+         */
+        ColorGradingTexture._noneEmptyLineRegex = /\S+/;
+        return ColorGradingTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.ColorGradingTexture = ColorGradingTexture;
+})(BABYLON || (BABYLON = {}));

+ 82 - 83
src/Materials/Textures/babylon.cubeTexture.js

@@ -1,83 +1,82 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var CubeTexture = (function (_super) {
-        __extends(CubeTexture, _super);
-        function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
-            _super.call(this, scene);
-            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-            this.name = rootUrl;
-            this.url = rootUrl;
-            this._noMipmap = noMipmap;
-            this.hasAlpha = false;
-            if (!rootUrl && !files) {
-                return;
-            }
-            this._texture = this._getFromCache(rootUrl, noMipmap);
-            if (!files) {
-                if (!extensions) {
-                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
-                }
-                files = [];
-                for (var index = 0; index < extensions.length; index++) {
-                    files.push(rootUrl + extensions[index]);
-                }
-                this._extensions = extensions;
-            }
-            this._files = files;
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-            this.isCube = true;
-            this._textureMatrix = BABYLON.Matrix.Identity();
-        }
-        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
-            return new CubeTexture("", scene, null, noMipmap, files);
-        };
-        // Methods
-        CubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
-            }
-        };
-        CubeTexture.prototype.getReflectionTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = BABYLON.SerializationHelper.Parse(function () {
-                return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-            }, parsedTexture, scene);
-            // Animations
-            if (parsedTexture.animations) {
-                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedTexture.animations[animationIndex];
-                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                }
-            }
-            return texture;
-        };
-        CubeTexture.prototype.clone = function () {
-            var _this = this;
-            return BABYLON.SerializationHelper.Clone(function () {
-                return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
-            }, this);
-        };
-        return CubeTexture;
-    }(BABYLON.BaseTexture));
-    BABYLON.CubeTexture = CubeTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.cubeTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var CubeTexture = (function (_super) {
+        __extends(CubeTexture, _super);
+        function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
+            _super.call(this, scene);
+            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+            this.name = rootUrl;
+            this.url = rootUrl;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+            if (!rootUrl && !files) {
+                return;
+            }
+            this._texture = this._getFromCache(rootUrl, noMipmap);
+            if (!files) {
+                if (!extensions) {
+                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
+                }
+                files = [];
+                for (var index = 0; index < extensions.length; index++) {
+                    files.push(rootUrl + extensions[index]);
+                }
+                this._extensions = extensions;
+            }
+            this._files = files;
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+            this.isCube = true;
+            this._textureMatrix = BABYLON.Matrix.Identity();
+        }
+        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
+            return new CubeTexture("", scene, null, noMipmap, files);
+        };
+        // Methods
+        CubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
+            }
+        };
+        CubeTexture.prototype.getReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = BABYLON.SerializationHelper.Parse(function () {
+                return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
+            }, parsedTexture, scene);
+            // Animations
+            if (parsedTexture.animations) {
+                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedTexture.animations[animationIndex];
+                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                }
+            }
+            return texture;
+        };
+        CubeTexture.prototype.clone = function () {
+            var _this = this;
+            return BABYLON.SerializationHelper.Clone(function () {
+                return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
+            }, this);
+        };
+        return CubeTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.CubeTexture = CubeTexture;
+})(BABYLON || (BABYLON = {}));

+ 251 - 252
src/Materials/Textures/babylon.fontTexture.js

@@ -1,252 +1,251 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This class given information about a given character.
-     */
-    var CharInfo = (function () {
-        function CharInfo() {
-        }
-        return CharInfo;
-    }());
-    BABYLON.CharInfo = CharInfo;
-    var FontTexture = (function (_super) {
-        __extends(FontTexture, _super);
-        /**
-         * Create a new instance of the FontTexture class
-         * @param name the name of the texture
-         * @param font the font to use, use the W3C CSS notation
-         * @param scene the scene that owns the texture
-         * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
-         * @param samplingMode the texture sampling mode
-         */
-        function FontTexture(name, font, scene, maxCharCount, samplingMode) {
-            if (maxCharCount === void 0) { maxCharCount = 200; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, true, false, samplingMode);
-            this._charInfos = {};
-            this._curCharCount = 0;
-            this._lastUpdateCharCount = -1;
-            this._usedCounter = 1;
-            this.name = name;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            // First canvas creation to determine the size of the texture to create
-            this._canvas = document.createElement("canvas");
-            this._context = this._canvas.getContext("2d");
-            this._context.font = font;
-            this._context.fillStyle = "white";
-            var res = this.getFontHeight(font);
-            this._lineHeight = res.height;
-            this._offset = res.offset - 1;
-            var maxCharWidth = this._context.measureText("W").width;
-            this._spaceWidth = this._context.measureText(" ").width;
-            // This is an approximate size, but should always be able to fit at least the maxCharCount
-            var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
-            var edge = Math.sqrt(totalEstSurface);
-            var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
-            // Create the texture that will store the font characters
-            this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
-            var textureSize = this.getSize();
-            // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
-            this._canvas = document.createElement("canvas");
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this._context = this._canvas.getContext("2d");
-            this._context.textBaseline = "top";
-            this._context.font = font;
-            this._context.fillStyle = "white";
-            this._context.imageSmoothingEnabled = false;
-            this._currentFreePosition = BABYLON.Vector2.Zero();
-            // Add the basic ASCII based characters
-            for (var i = 0x20; i < 0x7F; i++) {
-                var c = String.fromCharCode(i);
-                this.getChar(c);
-            }
-            this.update();
-        }
-        Object.defineProperty(FontTexture.prototype, "spaceWidth", {
-            get: function () {
-                return this._spaceWidth;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FontTexture.prototype, "lineHeight", {
-            get: function () {
-                return this._lineHeight;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        FontTexture.GetCachedFontTexture = function (scene, fontName) {
-            var s = scene;
-            if (!s.__fontTextureCache__) {
-                s.__fontTextureCache__ = new BABYLON.StringDictionary();
-            }
-            var dic = s.__fontTextureCache__;
-            var lfn = fontName.toLocaleLowerCase();
-            var ft = dic.get(lfn);
-            if (ft) {
-                ++ft._usedCounter;
-                return ft;
-            }
-            ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
-            dic.add(lfn, ft);
-            return ft;
-        };
-        FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
-            var s = scene;
-            var dic = s.__fontTextureCache__;
-            if (!dic) {
-                return;
-            }
-            var lfn = fontName.toLocaleLowerCase();
-            var font = dic.get(lfn);
-            if (--font._usedCounter === 0) {
-                dic.remove(lfn);
-                font.dispose();
-            }
-        };
-        /**
-         * Make sure the given char is present in the font map.
-         * @param char the character to get or add
-         * @return the CharInfo instance corresponding to the given character
-         */
-        FontTexture.prototype.getChar = function (char) {
-            if (char.length !== 1) {
-                return null;
-            }
-            var info = this._charInfos[char];
-            if (info) {
-                return info;
-            }
-            info = new CharInfo();
-            var measure = this._context.measureText(char);
-            var textureSize = this.getSize();
-            // we reached the end of the current line?
-            var xMargin = 2;
-            var yMargin = 2;
-            var width = measure.width;
-            if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
-                this._currentFreePosition.x = 0;
-                this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
-                // No more room?
-                if (this._currentFreePosition.y > textureSize.height) {
-                    return this.getChar("!");
-                }
-            }
-            // Draw the character in the texture
-            this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
-            // Fill the CharInfo object
-            info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
-            info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
-            info.charWidth = width;
-            // Add the info structure
-            this._charInfos[char] = info;
-            this._curCharCount++;
-            // Set the next position
-            this._currentFreePosition.x += width + xMargin;
-            return info;
-        };
-        FontTexture.prototype.measureText = function (text, tabulationSize) {
-            if (tabulationSize === void 0) { tabulationSize = 4; }
-            var maxWidth = 0;
-            var curWidth = 0;
-            var lineCount = 1;
-            var charxpos = 0;
-            // Parse each char of the string
-            for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
-                var char = text_1[_i];
-                // Next line feed?
-                if (char === "\n") {
-                    maxWidth = Math.max(maxWidth, curWidth);
-                    charxpos = 0;
-                    curWidth = 0;
-                    ++lineCount;
-                    continue;
-                }
-                // Tabulation ?
-                if (char === "\t") {
-                    var nextPos = charxpos + tabulationSize;
-                    nextPos = nextPos - (nextPos % tabulationSize);
-                    curWidth += (nextPos - charxpos) * this.spaceWidth;
-                    charxpos = nextPos;
-                    continue;
-                }
-                if (char < " ") {
-                    continue;
-                }
-                curWidth += this.getChar(char).charWidth;
-                ++charxpos;
-            }
-            maxWidth = Math.max(maxWidth, curWidth);
-            return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
-        };
-        // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
-        FontTexture.prototype.getFontHeight = function (font) {
-            var fontDraw = document.createElement("canvas");
-            var ctx = fontDraw.getContext('2d');
-            ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
-            ctx.textBaseline = 'top';
-            ctx.fillStyle = 'white';
-            ctx.font = font;
-            ctx.fillText('jH|', 0, 0);
-            var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
-            var start = -1;
-            var end = -1;
-            for (var row = 0; row < fontDraw.height; row++) {
-                for (var column = 0; column < fontDraw.width; column++) {
-                    var index = (row * fontDraw.width + column) * 4;
-                    if (pixels[index] === 0) {
-                        if (column === fontDraw.width - 1 && start !== -1) {
-                            end = row;
-                            row = fontDraw.height;
-                            break;
-                        }
-                        continue;
-                    }
-                    else {
-                        if (start === -1) {
-                            start = row;
-                        }
-                        break;
-                    }
-                }
-            }
-            return { height: end - start, offset: start - 1 };
-        };
-        Object.defineProperty(FontTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        FontTexture.prototype.getContext = function () {
-            return this._context;
-        };
-        /**
-         * Call this method when you've call getChar() at least one time, this will update the texture if needed.
-         * Don't be afraid to call it, if no new character was added, this method simply does nothing.
-         */
-        FontTexture.prototype.update = function () {
-            // Update only if there's new char added since the previous update
-            if (this._lastUpdateCharCount < this._curCharCount) {
-                this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
-                this._lastUpdateCharCount = this._curCharCount;
-            }
-        };
-        // cloning should be prohibited, there's no point to duplicate this texture at all
-        FontTexture.prototype.clone = function () {
-            return null;
-        };
-        return FontTexture;
-    }(BABYLON.Texture));
-    BABYLON.FontTexture = FontTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.fontTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This class given information about a given character.
+     */
+    var CharInfo = (function () {
+        function CharInfo() {
+        }
+        return CharInfo;
+    })();
+    BABYLON.CharInfo = CharInfo;
+    var FontTexture = (function (_super) {
+        __extends(FontTexture, _super);
+        /**
+         * Create a new instance of the FontTexture class
+         * @param name the name of the texture
+         * @param font the font to use, use the W3C CSS notation
+         * @param scene the scene that owns the texture
+         * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
+         * @param samplingMode the texture sampling mode
+         */
+        function FontTexture(name, font, scene, maxCharCount, samplingMode) {
+            if (maxCharCount === void 0) { maxCharCount = 200; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, true, false, samplingMode);
+            this._charInfos = {};
+            this._curCharCount = 0;
+            this._lastUpdateCharCount = -1;
+            this._usedCounter = 1;
+            this.name = name;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            // First canvas creation to determine the size of the texture to create
+            this._canvas = document.createElement("canvas");
+            this._context = this._canvas.getContext("2d");
+            this._context.font = font;
+            this._context.fillStyle = "white";
+            var res = this.getFontHeight(font);
+            this._lineHeight = res.height;
+            this._offset = res.offset - 1;
+            var maxCharWidth = this._context.measureText("W").width;
+            this._spaceWidth = this._context.measureText(" ").width;
+            // This is an approximate size, but should always be able to fit at least the maxCharCount
+            var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
+            var edge = Math.sqrt(totalEstSurface);
+            var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
+            // Create the texture that will store the font characters
+            this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
+            var textureSize = this.getSize();
+            // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
+            this._canvas = document.createElement("canvas");
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+            this._context.textBaseline = "top";
+            this._context.font = font;
+            this._context.fillStyle = "white";
+            this._context.imageSmoothingEnabled = false;
+            this._currentFreePosition = BABYLON.Vector2.Zero();
+            // Add the basic ASCII based characters
+            for (var i = 0x20; i < 0x7F; i++) {
+                var c = String.fromCharCode(i);
+                this.getChar(c);
+            }
+            this.update();
+        }
+        Object.defineProperty(FontTexture.prototype, "spaceWidth", {
+            get: function () {
+                return this._spaceWidth;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FontTexture.prototype, "lineHeight", {
+            get: function () {
+                return this._lineHeight;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        FontTexture.GetCachedFontTexture = function (scene, fontName) {
+            var s = scene;
+            if (!s.__fontTextureCache__) {
+                s.__fontTextureCache__ = new BABYLON.StringDictionary();
+            }
+            var dic = s.__fontTextureCache__;
+            var lfn = fontName.toLocaleLowerCase();
+            var ft = dic.get(lfn);
+            if (ft) {
+                ++ft._usedCounter;
+                return ft;
+            }
+            ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
+            dic.add(lfn, ft);
+            return ft;
+        };
+        FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
+            var s = scene;
+            var dic = s.__fontTextureCache__;
+            if (!dic) {
+                return;
+            }
+            var lfn = fontName.toLocaleLowerCase();
+            var font = dic.get(lfn);
+            if (--font._usedCounter === 0) {
+                dic.remove(lfn);
+                font.dispose();
+            }
+        };
+        /**
+         * Make sure the given char is present in the font map.
+         * @param char the character to get or add
+         * @return the CharInfo instance corresponding to the given character
+         */
+        FontTexture.prototype.getChar = function (char) {
+            if (char.length !== 1) {
+                return null;
+            }
+            var info = this._charInfos[char];
+            if (info) {
+                return info;
+            }
+            info = new CharInfo();
+            var measure = this._context.measureText(char);
+            var textureSize = this.getSize();
+            // we reached the end of the current line?
+            var xMargin = 2;
+            var yMargin = 2;
+            var width = measure.width;
+            if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
+                this._currentFreePosition.x = 0;
+                this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
+                // No more room?
+                if (this._currentFreePosition.y > textureSize.height) {
+                    return this.getChar("!");
+                }
+            }
+            // Draw the character in the texture
+            this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
+            // Fill the CharInfo object
+            info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
+            info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
+            info.charWidth = width;
+            // Add the info structure
+            this._charInfos[char] = info;
+            this._curCharCount++;
+            // Set the next position
+            this._currentFreePosition.x += width + xMargin;
+            return info;
+        };
+        FontTexture.prototype.measureText = function (text, tabulationSize) {
+            if (tabulationSize === void 0) { tabulationSize = 4; }
+            var maxWidth = 0;
+            var curWidth = 0;
+            var lineCount = 1;
+            var charxpos = 0;
+            // Parse each char of the string
+            for (var _i = 0; _i < text.length; _i++) {
+                var char = text[_i];
+                // Next line feed?
+                if (char === "\n") {
+                    maxWidth = Math.max(maxWidth, curWidth);
+                    charxpos = 0;
+                    curWidth = 0;
+                    ++lineCount;
+                    continue;
+                }
+                // Tabulation ?
+                if (char === "\t") {
+                    var nextPos = charxpos + tabulationSize;
+                    nextPos = nextPos - (nextPos % tabulationSize);
+                    curWidth += (nextPos - charxpos) * this.spaceWidth;
+                    charxpos = nextPos;
+                    continue;
+                }
+                if (char < " ") {
+                    continue;
+                }
+                curWidth += this.getChar(char).charWidth;
+                ++charxpos;
+            }
+            maxWidth = Math.max(maxWidth, curWidth);
+            return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
+        };
+        // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
+        FontTexture.prototype.getFontHeight = function (font) {
+            var fontDraw = document.createElement("canvas");
+            var ctx = fontDraw.getContext('2d');
+            ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
+            ctx.textBaseline = 'top';
+            ctx.fillStyle = 'white';
+            ctx.font = font;
+            ctx.fillText('jH|', 0, 0);
+            var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
+            var start = -1;
+            var end = -1;
+            for (var row = 0; row < fontDraw.height; row++) {
+                for (var column = 0; column < fontDraw.width; column++) {
+                    var index = (row * fontDraw.width + column) * 4;
+                    if (pixels[index] === 0) {
+                        if (column === fontDraw.width - 1 && start !== -1) {
+                            end = row;
+                            row = fontDraw.height;
+                            break;
+                        }
+                        continue;
+                    }
+                    else {
+                        if (start === -1) {
+                            start = row;
+                        }
+                        break;
+                    }
+                }
+            }
+            return { height: end - start, offset: start - 1 };
+        };
+        Object.defineProperty(FontTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        FontTexture.prototype.getContext = function () {
+            return this._context;
+        };
+        /**
+         * Call this method when you've call getChar() at least one time, this will update the texture if needed.
+         * Don't be afraid to call it, if no new character was added, this method simply does nothing.
+         */
+        FontTexture.prototype.update = function () {
+            // Update only if there's new char added since the previous update
+            if (this._lastUpdateCharCount < this._curCharCount) {
+                this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
+                this._lastUpdateCharCount = this._curCharCount;
+            }
+        };
+        // cloning should be prohibited, there's no point to duplicate this texture at all
+        FontTexture.prototype.clone = function () {
+            return null;
+        };
+        return FontTexture;
+    })(BABYLON.Texture);
+    BABYLON.FontTexture = FontTexture;
+})(BABYLON || (BABYLON = {}));

+ 447 - 448
src/Materials/Textures/babylon.hdrCubeTexture.js

@@ -1,448 +1,447 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This represents a texture coming from an HDR input.
-     *
-     * The only supported format is currently panorama picture stored in RGBE format.
-     * Example of such files can be found on HDRLib: http://hdrlib.com/
-     */
-    var HDRCubeTexture = (function (_super) {
-        __extends(HDRCubeTexture, _super);
-        /**
-         * Instantiates an HDRTexture from the following parameters.
-         *
-         * @param url The location of the HDR raw data (Panorama stored in RGBE format)
-         * @param scene The scene the texture will be used in
-         * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
-         * @param noMipmap Forces to not generate the mipmap if true
-         * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
-         * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
-         * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
-         */
-        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
-            if (noMipmap === void 0) { noMipmap = false; }
-            if (generateHarmonics === void 0) { generateHarmonics = true; }
-            if (useInGammaSpace === void 0) { useInGammaSpace = false; }
-            if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
-            _super.call(this, scene);
-            this._useInGammaSpace = false;
-            this._generateHarmonics = true;
-            this._isBABYLONPreprocessed = false;
-            /**
-             * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
-             */
-            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-            /**
-             * The spherical polynomial data extracted from the texture.
-             */
-            this.sphericalPolynomial = null;
-            /**
-             * Specifies wether the texture has been generated through the PMREMGenerator tool.
-             * This is usefull at run time to apply the good shader.
-             */
-            this.isPMREM = false;
-            if (!url) {
-                return;
-            }
-            this.name = url;
-            this.url = url;
-            this.hasAlpha = false;
-            this.isCube = true;
-            this._textureMatrix = BABYLON.Matrix.Identity();
-            if (size) {
-                this._isBABYLONPreprocessed = false;
-                this._noMipmap = noMipmap;
-                this._size = size;
-                this._useInGammaSpace = useInGammaSpace;
-                this._usePMREMGenerator = usePMREMGenerator &&
-                    scene.getEngine().getCaps().textureLOD &&
-                    this.getScene().getEngine().getCaps().textureFloat &&
-                    !this._useInGammaSpace;
-            }
-            else {
-                this._isBABYLONPreprocessed = true;
-                this._noMipmap = false;
-                this._useInGammaSpace = false;
-                this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
-                    this.getScene().getEngine().getCaps().textureFloat &&
-                    !this._useInGammaSpace;
-            }
-            this.isPMREM = this._usePMREMGenerator;
-            this._texture = this._getFromCache(url, this._noMipmap);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this.loadTexture();
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-        }
-        /**
-         * Occurs when the file is a preprocessed .babylon.hdr file.
-         */
-        HDRCubeTexture.prototype.loadBabylonTexture = function () {
-            var _this = this;
-            var mipLevels = 0;
-            var floatArrayView = null;
-            var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
-                var mips = [];
-                var startIndex = 30;
-                for (var level = 0; level < mipLevels; level++) {
-                    mips.push([]);
-                    // Fill each pixel of the mip level.
-                    var faceSize = Math.pow(_this._size >> level, 2) * 3;
-                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
-                        var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
-                        mips[level].push(faceData);
-                        startIndex += faceSize;
-                    }
-                }
-                return mips;
-            } : null;
-            var callback = function (buffer) {
-                // Create Native Array Views
-                var intArrayView = new Int32Array(buffer);
-                floatArrayView = new Float32Array(buffer);
-                // Fill header.
-                var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
-                _this._size = intArrayView[1]; // CubeMap max mip face size.
-                // Update Texture Information.
-                _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
-                // Fill polynomial information.
-                _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
-                _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
-                _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
-                _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
-                _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
-                _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
-                _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
-                _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
-                _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
-                _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
-                // Fill pixel data.
-                mipLevels = intArrayView[29]; // Number of mip levels.
-                var startIndex = 30;
-                var data = [];
-                var faceSize = Math.pow(_this._size, 2) * 3;
-                for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
-                    data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
-                    startIndex += faceSize;
-                }
-                var results = [];
-                var byteArray = null;
-                // Push each faces.
-                for (var k = 0; k < 6; k++) {
-                    var dataFace = null;
-                    // If special cases.
-                    if (!mipmapGenerator) {
-                        var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
-                        dataFace = data[j];
-                        if (!_this.getScene().getEngine().getCaps().textureFloat) {
-                            // 3 channels of 1 bytes per pixel in bytes.
-                            var byteBuffer = new ArrayBuffer(faceSize);
-                            byteArray = new Uint8Array(byteBuffer);
-                        }
-                        for (var i = 0; i < _this._size * _this._size; i++) {
-                            // Put in gamma space if requested.
-                            if (_this._useInGammaSpace) {
-                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
-                            }
-                            // Convert to int texture for fallback.
-                            if (byteArray) {
-                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
-                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
-                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
-                                // May use luminance instead if the result is not accurate.
-                                var max = Math.max(Math.max(r, g), b);
-                                if (max > 255) {
-                                    var scale = 255 / max;
-                                    r *= scale;
-                                    g *= scale;
-                                    b *= scale;
-                                }
-                                byteArray[(i * 3) + 0] = r;
-                                byteArray[(i * 3) + 1] = g;
-                                byteArray[(i * 3) + 2] = b;
-                            }
-                        }
-                    }
-                    else {
-                        dataFace = data[k];
-                    }
-                    // Fill the array accordingly.
-                    if (byteArray) {
-                        results.push(byteArray);
-                    }
-                    else {
-                        results.push(dataFace);
-                    }
-                }
-                return results;
-            };
-            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
-        };
-        /**
-         * Occurs when the file is raw .hdr file.
-         */
-        HDRCubeTexture.prototype.loadHDRTexture = function () {
-            var _this = this;
-            var callback = function (buffer) {
-                // Extract the raw linear data.
-                var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
-                // Generate harmonics if needed.
-                if (_this._generateHarmonics) {
-                    _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
-                }
-                var results = [];
-                var byteArray = null;
-                // Push each faces.
-                for (var j = 0; j < 6; j++) {
-                    // Create uintarray fallback.
-                    if (!_this.getScene().getEngine().getCaps().textureFloat) {
-                        // 3 channels of 1 bytes per pixel in bytes.
-                        var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
-                        byteArray = new Uint8Array(byteBuffer);
-                    }
-                    var dataFace = data[HDRCubeTexture._facesMapping[j]];
-                    // If special cases.
-                    if (_this._useInGammaSpace || byteArray) {
-                        for (var i = 0; i < _this._size * _this._size; i++) {
-                            // Put in gamma space if requested.
-                            if (_this._useInGammaSpace) {
-                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
-                            }
-                            // Convert to int texture for fallback.
-                            if (byteArray) {
-                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
-                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
-                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
-                                // May use luminance instead if the result is not accurate.
-                                var max = Math.max(Math.max(r, g), b);
-                                if (max > 255) {
-                                    var scale = 255 / max;
-                                    r *= scale;
-                                    g *= scale;
-                                    b *= scale;
-                                }
-                                byteArray[(i * 3) + 0] = r;
-                                byteArray[(i * 3) + 1] = g;
-                                byteArray[(i * 3) + 2] = b;
-                            }
-                        }
-                    }
-                    if (byteArray) {
-                        results.push(byteArray);
-                    }
-                    else {
-                        results.push(dataFace);
-                    }
-                }
-                return results;
-            };
-            var mipmapGenerator = null;
-            if (!this._noMipmap &&
-                this._usePMREMGenerator) {
-                mipmapGenerator = function (data) {
-                    // Custom setup of the generator matching with the PBR shader values.
-                    var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
-                    return generator.filterCubeMap();
-                };
-            }
-            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
-        };
-        /**
-         * Starts the loading process of the texture.
-         */
-        HDRCubeTexture.prototype.loadTexture = function () {
-            if (this._isBABYLONPreprocessed) {
-                this.loadBabylonTexture();
-            }
-            else {
-                this.loadHDRTexture();
-            }
-        };
-        HDRCubeTexture.prototype.clone = function () {
-            var size = this._isBABYLONPreprocessed ? null : this._size;
-            var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
-            // Base texture
-            newTexture.level = this.level;
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            newTexture.coordinatesIndex = this.coordinatesIndex;
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        // Methods
-        HDRCubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-            if (!this._texture) {
-                this.loadTexture();
-            }
-        };
-        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
-                var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
-                texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        };
-        HDRCubeTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.isCube = true;
-            serializationObject.level = this.level;
-            serializationObject.size = this._size;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            serializationObject.useInGammaSpace = this._useInGammaSpace;
-            serializationObject.generateHarmonics = this._generateHarmonics;
-            serializationObject.usePMREMGenerator = this._usePMREMGenerator;
-            serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
-            return serializationObject;
-        };
-        /**
-         * Saves as a file the data contained in the texture in a binary format.
-         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
-         * as the spherical used in the lighting.
-         * @param url The HDR file url.
-         * @param size The size of the texture data to generate (one of the cubemap face desired width).
-         * @param onError Method called if any error happens during download.
-         * @return The packed binary data.
-         */
-        HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
-            if (onError === void 0) { onError = null; }
-            var callback = function (buffer) {
-                var data = new Blob([buffer], { type: 'application/octet-stream' });
-                // Returns a URL you can use as a href.
-                var objUrl = window.URL.createObjectURL(data);
-                // Simulates a link to it and click to dowload.
-                var a = document.createElement("a");
-                document.body.appendChild(a);
-                a.style.display = "none";
-                a.href = objUrl;
-                a.download = "envmap.babylon.hdr";
-                a.click();
-            };
-            HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
-        };
-        /**
-         * Serializes the data contained in the texture in a binary format.
-         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
-         * as the spherical used in the lighting.
-         * @param url The HDR file url.
-         * @param size The size of the texture data to generate (one of the cubemap face desired width).
-         * @param onError Method called if any error happens during download.
-         * @return The packed binary data.
-         */
-        HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
-            if (onError === void 0) { onError = null; }
-            // Needs the url tho create the texture.
-            if (!url) {
-                return null;
-            }
-            // Check Power of two size.
-            if (!BABYLON.Tools.IsExponentOfTwo(size)) {
-                return null;
-            }
-            var getDataCallback = function (dataBuffer) {
-                // Extract the raw linear data.
-                var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
-                // Generate harmonics if needed.
-                var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
-                // Generate seamless faces
-                var mipGeneratorArray = [];
-                // Data are known to be in +X +Y +Z -X -Y -Z
-                // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
-                mipGeneratorArray.push(cubeData.right); // +X
-                mipGeneratorArray.push(cubeData.left); // -X
-                mipGeneratorArray.push(cubeData.up); // +Y
-                mipGeneratorArray.push(cubeData.down); // -Y
-                mipGeneratorArray.push(cubeData.front); // +Z
-                mipGeneratorArray.push(cubeData.back); // -Z
-                // Custom setup of the generator matching with the PBR shader values.
-                var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
-                var mippedData = generator.filterCubeMap();
-                // Compute required byte length.
-                var byteLength = 1 * 4; // Raw Data Version int32.
-                byteLength += 4; // CubeMap max mip face size int32.
-                byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
-                // Add data size.
-                byteLength += 4; // Number of mip levels int32.
-                for (var level = 0; level < mippedData.length; level++) {
-                    var mipSize = size >> level;
-                    byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
-                }
-                // Prepare binary structure.
-                var buffer = new ArrayBuffer(byteLength);
-                var intArrayView = new Int32Array(buffer);
-                var floatArrayView = new Float32Array(buffer);
-                // Fill header.
-                intArrayView[0] = 1; // Version 1.
-                intArrayView[1] = size; // CubeMap max mip face size.
-                // Fill polynomial information.
-                sphericalPolynomial.x.toArray(floatArrayView, 2);
-                sphericalPolynomial.y.toArray(floatArrayView, 5);
-                sphericalPolynomial.z.toArray(floatArrayView, 8);
-                sphericalPolynomial.xx.toArray(floatArrayView, 11);
-                sphericalPolynomial.yy.toArray(floatArrayView, 14);
-                sphericalPolynomial.zz.toArray(floatArrayView, 17);
-                sphericalPolynomial.xy.toArray(floatArrayView, 20);
-                sphericalPolynomial.yz.toArray(floatArrayView, 23);
-                sphericalPolynomial.zx.toArray(floatArrayView, 26);
-                // Fill pixel data.
-                intArrayView[29] = mippedData.length; // Number of mip levels.
-                var startIndex = 30;
-                for (var level = 0; level < mippedData.length; level++) {
-                    // Fill each pixel of the mip level.
-                    var faceSize = Math.pow(size >> level, 2) * 3;
-                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
-                        floatArrayView.set(mippedData[level][faceIndex], startIndex);
-                        startIndex += faceSize;
-                    }
-                }
-                // Callback.
-                callback(buffer);
-            };
-            // Download and process.
-            BABYLON.Tools.LoadFile(url, function (data) {
-                getDataCallback(data);
-            }, null, null, true, onError);
-        };
-        HDRCubeTexture._facesMapping = [
-            "right",
-            "up",
-            "front",
-            "left",
-            "down",
-            "back"
-        ];
-        return HDRCubeTexture;
-    }(BABYLON.BaseTexture));
-    BABYLON.HDRCubeTexture = HDRCubeTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.hdrcubetexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This represents a texture coming from an HDR input.
+     *
+     * The only supported format is currently panorama picture stored in RGBE format.
+     * Example of such files can be found on HDRLib: http://hdrlib.com/
+     */
+    var HDRCubeTexture = (function (_super) {
+        __extends(HDRCubeTexture, _super);
+        /**
+         * Instantiates an HDRTexture from the following parameters.
+         *
+         * @param url The location of the HDR raw data (Panorama stored in RGBE format)
+         * @param scene The scene the texture will be used in
+         * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
+         * @param noMipmap Forces to not generate the mipmap if true
+         * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
+         * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
+         * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
+         */
+        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
+            if (noMipmap === void 0) { noMipmap = false; }
+            if (generateHarmonics === void 0) { generateHarmonics = true; }
+            if (useInGammaSpace === void 0) { useInGammaSpace = false; }
+            if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
+            _super.call(this, scene);
+            this._useInGammaSpace = false;
+            this._generateHarmonics = true;
+            this._isBABYLONPreprocessed = false;
+            /**
+             * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
+             */
+            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+            /**
+             * The spherical polynomial data extracted from the texture.
+             */
+            this.sphericalPolynomial = null;
+            /**
+             * Specifies wether the texture has been generated through the PMREMGenerator tool.
+             * This is usefull at run time to apply the good shader.
+             */
+            this.isPMREM = false;
+            if (!url) {
+                return;
+            }
+            this.name = url;
+            this.url = url;
+            this.hasAlpha = false;
+            this.isCube = true;
+            this._textureMatrix = BABYLON.Matrix.Identity();
+            if (size) {
+                this._isBABYLONPreprocessed = false;
+                this._noMipmap = noMipmap;
+                this._size = size;
+                this._useInGammaSpace = useInGammaSpace;
+                this._usePMREMGenerator = usePMREMGenerator &&
+                    scene.getEngine().getCaps().textureLOD &&
+                    this.getScene().getEngine().getCaps().textureFloat &&
+                    !this._useInGammaSpace;
+            }
+            else {
+                this._isBABYLONPreprocessed = true;
+                this._noMipmap = false;
+                this._useInGammaSpace = false;
+                this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
+                    this.getScene().getEngine().getCaps().textureFloat &&
+                    !this._useInGammaSpace;
+            }
+            this.isPMREM = this._usePMREMGenerator;
+            this._texture = this._getFromCache(url, this._noMipmap);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this.loadTexture();
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+        }
+        /**
+         * Occurs when the file is a preprocessed .babylon.hdr file.
+         */
+        HDRCubeTexture.prototype.loadBabylonTexture = function () {
+            var _this = this;
+            var mipLevels = 0;
+            var floatArrayView = null;
+            var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
+                var mips = [];
+                var startIndex = 30;
+                for (var level = 0; level < mipLevels; level++) {
+                    mips.push([]);
+                    // Fill each pixel of the mip level.
+                    var faceSize = Math.pow(_this._size >> level, 2) * 3;
+                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
+                        var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
+                        mips[level].push(faceData);
+                        startIndex += faceSize;
+                    }
+                }
+                return mips;
+            } : null;
+            var callback = function (buffer) {
+                // Create Native Array Views
+                var intArrayView = new Int32Array(buffer);
+                floatArrayView = new Float32Array(buffer);
+                // Fill header.
+                var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
+                _this._size = intArrayView[1]; // CubeMap max mip face size.
+                // Update Texture Information.
+                _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
+                // Fill polynomial information.
+                _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
+                _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
+                _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
+                _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
+                _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
+                _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
+                _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
+                _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
+                _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
+                _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
+                // Fill pixel data.
+                mipLevels = intArrayView[29]; // Number of mip levels.
+                var startIndex = 30;
+                var data = [];
+                var faceSize = Math.pow(_this._size, 2) * 3;
+                for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
+                    data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
+                    startIndex += faceSize;
+                }
+                var results = [];
+                var byteArray = null;
+                // Push each faces.
+                for (var k = 0; k < 6; k++) {
+                    var dataFace = null;
+                    // If special cases.
+                    if (!mipmapGenerator) {
+                        var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
+                        dataFace = data[j];
+                        if (!_this.getScene().getEngine().getCaps().textureFloat) {
+                            // 3 channels of 1 bytes per pixel in bytes.
+                            var byteBuffer = new ArrayBuffer(faceSize);
+                            byteArray = new Uint8Array(byteBuffer);
+                        }
+                        for (var i = 0; i < _this._size * _this._size; i++) {
+                            // Put in gamma space if requested.
+                            if (_this._useInGammaSpace) {
+                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
+                            }
+                            // Convert to int texture for fallback.
+                            if (byteArray) {
+                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
+                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
+                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
+                                // May use luminance instead if the result is not accurate.
+                                var max = Math.max(Math.max(r, g), b);
+                                if (max > 255) {
+                                    var scale = 255 / max;
+                                    r *= scale;
+                                    g *= scale;
+                                    b *= scale;
+                                }
+                                byteArray[(i * 3) + 0] = r;
+                                byteArray[(i * 3) + 1] = g;
+                                byteArray[(i * 3) + 2] = b;
+                            }
+                        }
+                    }
+                    else {
+                        dataFace = data[k];
+                    }
+                    // Fill the array accordingly.
+                    if (byteArray) {
+                        results.push(byteArray);
+                    }
+                    else {
+                        results.push(dataFace);
+                    }
+                }
+                return results;
+            };
+            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
+        };
+        /**
+         * Occurs when the file is raw .hdr file.
+         */
+        HDRCubeTexture.prototype.loadHDRTexture = function () {
+            var _this = this;
+            var callback = function (buffer) {
+                // Extract the raw linear data.
+                var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
+                // Generate harmonics if needed.
+                if (_this._generateHarmonics) {
+                    _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
+                }
+                var results = [];
+                var byteArray = null;
+                // Push each faces.
+                for (var j = 0; j < 6; j++) {
+                    // Create uintarray fallback.
+                    if (!_this.getScene().getEngine().getCaps().textureFloat) {
+                        // 3 channels of 1 bytes per pixel in bytes.
+                        var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
+                        byteArray = new Uint8Array(byteBuffer);
+                    }
+                    var dataFace = data[HDRCubeTexture._facesMapping[j]];
+                    // If special cases.
+                    if (_this._useInGammaSpace || byteArray) {
+                        for (var i = 0; i < _this._size * _this._size; i++) {
+                            // Put in gamma space if requested.
+                            if (_this._useInGammaSpace) {
+                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
+                            }
+                            // Convert to int texture for fallback.
+                            if (byteArray) {
+                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
+                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
+                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
+                                // May use luminance instead if the result is not accurate.
+                                var max = Math.max(Math.max(r, g), b);
+                                if (max > 255) {
+                                    var scale = 255 / max;
+                                    r *= scale;
+                                    g *= scale;
+                                    b *= scale;
+                                }
+                                byteArray[(i * 3) + 0] = r;
+                                byteArray[(i * 3) + 1] = g;
+                                byteArray[(i * 3) + 2] = b;
+                            }
+                        }
+                    }
+                    if (byteArray) {
+                        results.push(byteArray);
+                    }
+                    else {
+                        results.push(dataFace);
+                    }
+                }
+                return results;
+            };
+            var mipmapGenerator = null;
+            if (!this._noMipmap &&
+                this._usePMREMGenerator) {
+                mipmapGenerator = function (data) {
+                    // Custom setup of the generator matching with the PBR shader values.
+                    var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
+                    return generator.filterCubeMap();
+                };
+            }
+            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
+        };
+        /**
+         * Starts the loading process of the texture.
+         */
+        HDRCubeTexture.prototype.loadTexture = function () {
+            if (this._isBABYLONPreprocessed) {
+                this.loadBabylonTexture();
+            }
+            else {
+                this.loadHDRTexture();
+            }
+        };
+        HDRCubeTexture.prototype.clone = function () {
+            var size = this._isBABYLONPreprocessed ? null : this._size;
+            var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
+            // Base texture
+            newTexture.level = this.level;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        // Methods
+        HDRCubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+            if (!this._texture) {
+                this.loadTexture();
+            }
+        };
+        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
+                var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
+                texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
+                texture.name = parsedTexture.name;
+                texture.hasAlpha = parsedTexture.hasAlpha;
+                texture.level = parsedTexture.level;
+                texture.coordinatesMode = parsedTexture.coordinatesMode;
+            }
+            return texture;
+        };
+        HDRCubeTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.isCube = true;
+            serializationObject.level = this.level;
+            serializationObject.size = this._size;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            serializationObject.useInGammaSpace = this._useInGammaSpace;
+            serializationObject.generateHarmonics = this._generateHarmonics;
+            serializationObject.usePMREMGenerator = this._usePMREMGenerator;
+            serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
+            return serializationObject;
+        };
+        /**
+         * Saves as a file the data contained in the texture in a binary format.
+         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
+         * as the spherical used in the lighting.
+         * @param url The HDR file url.
+         * @param size The size of the texture data to generate (one of the cubemap face desired width).
+         * @param onError Method called if any error happens during download.
+         * @return The packed binary data.
+         */
+        HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
+            if (onError === void 0) { onError = null; }
+            var callback = function (buffer) {
+                var data = new Blob([buffer], { type: 'application/octet-stream' });
+                // Returns a URL you can use as a href.
+                var objUrl = window.URL.createObjectURL(data);
+                // Simulates a link to it and click to dowload.
+                var a = document.createElement("a");
+                document.body.appendChild(a);
+                a.style.display = "none";
+                a.href = objUrl;
+                a.download = "envmap.babylon.hdr";
+                a.click();
+            };
+            HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
+        };
+        /**
+         * Serializes the data contained in the texture in a binary format.
+         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
+         * as the spherical used in the lighting.
+         * @param url The HDR file url.
+         * @param size The size of the texture data to generate (one of the cubemap face desired width).
+         * @param onError Method called if any error happens during download.
+         * @return The packed binary data.
+         */
+        HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
+            if (onError === void 0) { onError = null; }
+            // Needs the url tho create the texture.
+            if (!url) {
+                return null;
+            }
+            // Check Power of two size.
+            if (!BABYLON.Tools.IsExponentOfTwo(size)) {
+                return null;
+            }
+            var getDataCallback = function (dataBuffer) {
+                // Extract the raw linear data.
+                var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
+                // Generate harmonics if needed.
+                var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
+                // Generate seamless faces
+                var mipGeneratorArray = [];
+                // Data are known to be in +X +Y +Z -X -Y -Z
+                // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
+                mipGeneratorArray.push(cubeData.right); // +X
+                mipGeneratorArray.push(cubeData.left); // -X
+                mipGeneratorArray.push(cubeData.up); // +Y
+                mipGeneratorArray.push(cubeData.down); // -Y
+                mipGeneratorArray.push(cubeData.front); // +Z
+                mipGeneratorArray.push(cubeData.back); // -Z
+                // Custom setup of the generator matching with the PBR shader values.
+                var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
+                var mippedData = generator.filterCubeMap();
+                // Compute required byte length.
+                var byteLength = 1 * 4; // Raw Data Version int32.
+                byteLength += 4; // CubeMap max mip face size int32.
+                byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
+                // Add data size.
+                byteLength += 4; // Number of mip levels int32.
+                for (var level = 0; level < mippedData.length; level++) {
+                    var mipSize = size >> level;
+                    byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
+                }
+                // Prepare binary structure.
+                var buffer = new ArrayBuffer(byteLength);
+                var intArrayView = new Int32Array(buffer);
+                var floatArrayView = new Float32Array(buffer);
+                // Fill header.
+                intArrayView[0] = 1; // Version 1.
+                intArrayView[1] = size; // CubeMap max mip face size.
+                // Fill polynomial information.
+                sphericalPolynomial.x.toArray(floatArrayView, 2);
+                sphericalPolynomial.y.toArray(floatArrayView, 5);
+                sphericalPolynomial.z.toArray(floatArrayView, 8);
+                sphericalPolynomial.xx.toArray(floatArrayView, 11);
+                sphericalPolynomial.yy.toArray(floatArrayView, 14);
+                sphericalPolynomial.zz.toArray(floatArrayView, 17);
+                sphericalPolynomial.xy.toArray(floatArrayView, 20);
+                sphericalPolynomial.yz.toArray(floatArrayView, 23);
+                sphericalPolynomial.zx.toArray(floatArrayView, 26);
+                // Fill pixel data.
+                intArrayView[29] = mippedData.length; // Number of mip levels.
+                var startIndex = 30;
+                for (var level = 0; level < mippedData.length; level++) {
+                    // Fill each pixel of the mip level.
+                    var faceSize = Math.pow(size >> level, 2) * 3;
+                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
+                        floatArrayView.set(mippedData[level][faceIndex], startIndex);
+                        startIndex += faceSize;
+                    }
+                }
+                // Callback.
+                callback(buffer);
+            };
+            // Download and process.
+            BABYLON.Tools.LoadFile(url, function (data) {
+                getDataCallback(data);
+            }, null, null, true, onError);
+        };
+        HDRCubeTexture._facesMapping = [
+            "right",
+            "up",
+            "front",
+            "left",
+            "down",
+            "back"
+        ];
+        return HDRCubeTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.HDRCubeTexture = HDRCubeTexture;
+})(BABYLON || (BABYLON = {}));

+ 110 - 111
src/Materials/Textures/babylon.mapTexture.js

@@ -1,111 +1,110 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var MapTexture = (function (_super) {
-        __extends(MapTexture, _super);
-        function MapTexture(name, scene, size, samplingMode) {
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, true, false, samplingMode);
-            this.name = name;
-            this._size = size;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            // Create the rectPackMap that will allocate portion of the texture
-            this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
-            // Create the texture that will store the content
-            this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
-        }
-        /**
-         * Allocate a rectangle of a given size in the texture map
-         * @param size the size of the rectangle to allocation
-         * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
-         */
-        MapTexture.prototype.allocateRect = function (size) {
-            return this._rectPackingMap.addRect(size);
-        };
-        /**
-         * Free a given rectangle from the texture map
-         * @param rectInfo the instance corresponding to the rect to free.
-         */
-        MapTexture.prototype.freeRect = function (rectInfo) {
-            if (rectInfo) {
-                rectInfo.freeContent();
-            }
-        };
-        Object.defineProperty(MapTexture.prototype, "freeSpace", {
-            /**
-             * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
-             * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
-             * @returns {}
-             */
-            get: function () {
-                return this._rectPackingMap.freeSpace;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Bind the texture to the rendering engine to render in the zone of a given rectangle.
-         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
-         * Don't forget to call unbindTexture when you're done rendering
-         * @param rect the zone to render to
-         * @param clear true to clear the portion's color/depth data
-         */
-        MapTexture.prototype.bindTextureForRect = function (rect, clear) {
-            return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
-        };
-        /**
-         * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
-         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
-         * Don't forget to call unbindTexture when you're done rendering
-         * @param pos the position into the texture
-         * @param size the portion to fit the clip space to
-         * @param clear true to clear the portion's color/depth data
-         */
-        MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
-            var engine = this.getScene().getEngine();
-            engine.bindFramebuffer(this._texture);
-            this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
-            if (clear) {
-                // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
-                engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
-            }
-        };
-        /**
-         * Unbind the texture map from the rendering engine.
-         * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
-         * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
-         */
-        MapTexture.prototype.unbindTexture = function (dumpForDebug) {
-            // Dump ?
-            if (dumpForDebug) {
-                BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
-            }
-            var engine = this.getScene().getEngine();
-            if (this._replacedViewport) {
-                engine.setViewport(this._replacedViewport);
-                this._replacedViewport = null;
-            }
-            engine.unBindFramebuffer(this._texture);
-        };
-        Object.defineProperty(MapTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
-        // Anyway, there's not much point to use this method for this kind of texture I guess
-        MapTexture.prototype.clone = function () {
-            return null;
-        };
-        return MapTexture;
-    }(BABYLON.Texture));
-    BABYLON.MapTexture = MapTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.mapTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var MapTexture = (function (_super) {
+        __extends(MapTexture, _super);
+        function MapTexture(name, scene, size, samplingMode) {
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, true, false, samplingMode);
+            this.name = name;
+            this._size = size;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            // Create the rectPackMap that will allocate portion of the texture
+            this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
+            // Create the texture that will store the content
+            this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
+        }
+        /**
+         * Allocate a rectangle of a given size in the texture map
+         * @param size the size of the rectangle to allocation
+         * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
+         */
+        MapTexture.prototype.allocateRect = function (size) {
+            return this._rectPackingMap.addRect(size);
+        };
+        /**
+         * Free a given rectangle from the texture map
+         * @param rectInfo the instance corresponding to the rect to free.
+         */
+        MapTexture.prototype.freeRect = function (rectInfo) {
+            if (rectInfo) {
+                rectInfo.freeContent();
+            }
+        };
+        Object.defineProperty(MapTexture.prototype, "freeSpace", {
+            /**
+             * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
+             * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
+             * @returns {}
+             */
+            get: function () {
+                return this._rectPackingMap.freeSpace;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Bind the texture to the rendering engine to render in the zone of a given rectangle.
+         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
+         * Don't forget to call unbindTexture when you're done rendering
+         * @param rect the zone to render to
+         * @param clear true to clear the portion's color/depth data
+         */
+        MapTexture.prototype.bindTextureForRect = function (rect, clear) {
+            return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
+        };
+        /**
+         * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
+         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
+         * Don't forget to call unbindTexture when you're done rendering
+         * @param pos the position into the texture
+         * @param size the portion to fit the clip space to
+         * @param clear true to clear the portion's color/depth data
+         */
+        MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
+            var engine = this.getScene().getEngine();
+            engine.bindFramebuffer(this._texture);
+            this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
+            if (clear) {
+                // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
+                engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
+            }
+        };
+        /**
+         * Unbind the texture map from the rendering engine.
+         * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
+         * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
+         */
+        MapTexture.prototype.unbindTexture = function (dumpForDebug) {
+            // Dump ?
+            if (dumpForDebug) {
+                BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
+            }
+            var engine = this.getScene().getEngine();
+            if (this._replacedViewport) {
+                engine.setViewport(this._replacedViewport);
+                this._replacedViewport = null;
+            }
+            engine.unBindFramebuffer(this._texture);
+        };
+        Object.defineProperty(MapTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
+        // Anyway, there's not much point to use this method for this kind of texture I guess
+        MapTexture.prototype.clone = function () {
+            return null;
+        };
+        return MapTexture;
+    })(BABYLON.Texture);
+    BABYLON.MapTexture = MapTexture;
+})(BABYLON || (BABYLON = {}));

+ 54 - 55
src/Materials/Textures/babylon.mirrorTexture.js

@@ -1,55 +1,54 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var MirrorTexture = (function (_super) {
-        __extends(MirrorTexture, _super);
-        function MirrorTexture(name, size, scene, generateMipMaps) {
-            var _this = this;
-            _super.call(this, name, size, scene, generateMipMaps, true);
-            this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
-            this._transformMatrix = BABYLON.Matrix.Zero();
-            this._mirrorMatrix = BABYLON.Matrix.Zero();
-            this.onBeforeRenderObservable.add(function () {
-                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
-                _this._savedViewMatrix = scene.getViewMatrix();
-                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
-                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
-                scene.clipPlane = _this.mirrorPlane;
-                scene.getEngine().cullBackFaces = false;
-                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
-            });
-            this.onAfterRenderObservable.add(function () {
-                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
-                scene.getEngine().cullBackFaces = true;
-                scene._mirroredCameraPosition = null;
-                delete scene.clipPlane;
-            });
-        }
-        MirrorTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // Mirror Texture
-            newTexture.mirrorPlane = this.mirrorPlane.clone();
-            newTexture.renderList = this.renderList.slice(0);
-            return newTexture;
-        };
-        MirrorTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
-            return serializationObject;
-        };
-        return MirrorTexture;
-    }(BABYLON.RenderTargetTexture));
-    BABYLON.MirrorTexture = MirrorTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.mirrorTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var MirrorTexture = (function (_super) {
+        __extends(MirrorTexture, _super);
+        function MirrorTexture(name, size, scene, generateMipMaps) {
+            var _this = this;
+            _super.call(this, name, size, scene, generateMipMaps, true);
+            this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
+            this._transformMatrix = BABYLON.Matrix.Zero();
+            this._mirrorMatrix = BABYLON.Matrix.Zero();
+            this.onBeforeRenderObservable.add(function () {
+                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
+                _this._savedViewMatrix = scene.getViewMatrix();
+                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
+                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
+                scene.clipPlane = _this.mirrorPlane;
+                scene.getEngine().cullBackFaces = false;
+                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
+            });
+            this.onAfterRenderObservable.add(function () {
+                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
+                scene.getEngine().cullBackFaces = true;
+                scene._mirroredCameraPosition = null;
+                delete scene.clipPlane;
+            });
+        }
+        MirrorTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // Mirror Texture
+            newTexture.mirrorPlane = this.mirrorPlane.clone();
+            newTexture.renderList = this.renderList.slice(0);
+            return newTexture;
+        };
+        MirrorTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
+            return serializationObject;
+        };
+        return MirrorTexture;
+    })(BABYLON.RenderTargetTexture);
+    BABYLON.MirrorTexture = MirrorTexture;
+})(BABYLON || (BABYLON = {}));

+ 57 - 58
src/Materials/Textures/babylon.rawTexture.js

@@ -1,58 +1,57 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var RawTexture = (function (_super) {
-        __extends(RawTexture, _super);
-        function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps, invertY);
-            this.format = format;
-            this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        }
-        RawTexture.prototype.update = function (data) {
-            this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
-        };
-        // Statics
-        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        return RawTexture;
-    }(BABYLON.Texture));
-    BABYLON.RawTexture = RawTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.rawTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var RawTexture = (function (_super) {
+        __extends(RawTexture, _super);
+        function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps, invertY);
+            this.format = format;
+            this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+        }
+        RawTexture.prototype.update = function (data) {
+            this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
+        };
+        // Statics
+        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        return RawTexture;
+    })(BABYLON.Texture);
+    BABYLON.RawTexture = RawTexture;
+})(BABYLON || (BABYLON = {}));

+ 52 - 53
src/Materials/Textures/babylon.refractionTexture.js

@@ -1,53 +1,52 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-    * Creates a refraction texture used by refraction channel of the standard material.
-    * @param name the texture name
-    * @param size size of the underlying texture
-    * @param scene root scene
-    */
-    var RefractionTexture = (function (_super) {
-        __extends(RefractionTexture, _super);
-        function RefractionTexture(name, size, scene, generateMipMaps) {
-            var _this = this;
-            _super.call(this, name, size, scene, generateMipMaps, true);
-            this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
-            this.depth = 2.0;
-            this.onBeforeRenderObservable.add(function () {
-                scene.clipPlane = _this.refractionPlane;
-            });
-            this.onAfterRenderObservable.add(function () {
-                delete scene.clipPlane;
-            });
-        }
-        RefractionTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // Refraction Texture
-            newTexture.refractionPlane = this.refractionPlane.clone();
-            newTexture.renderList = this.renderList.slice(0);
-            newTexture.depth = this.depth;
-            return newTexture;
-        };
-        RefractionTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.mirrorPlane = this.refractionPlane.asArray();
-            serializationObject.depth = this.depth;
-            return serializationObject;
-        };
-        return RefractionTexture;
-    }(BABYLON.RenderTargetTexture));
-    BABYLON.RefractionTexture = RefractionTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.refractionTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+    * Creates a refraction texture used by refraction channel of the standard material.
+    * @param name the texture name
+    * @param size size of the underlying texture
+    * @param scene root scene
+    */
+    var RefractionTexture = (function (_super) {
+        __extends(RefractionTexture, _super);
+        function RefractionTexture(name, size, scene, generateMipMaps) {
+            var _this = this;
+            _super.call(this, name, size, scene, generateMipMaps, true);
+            this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
+            this.depth = 2.0;
+            this.onBeforeRenderObservable.add(function () {
+                scene.clipPlane = _this.refractionPlane;
+            });
+            this.onAfterRenderObservable.add(function () {
+                delete scene.clipPlane;
+            });
+        }
+        RefractionTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // Refraction Texture
+            newTexture.refractionPlane = this.refractionPlane.clone();
+            newTexture.renderList = this.renderList.slice(0);
+            newTexture.depth = this.depth;
+            return newTexture;
+        };
+        RefractionTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.mirrorPlane = this.refractionPlane.asArray();
+            serializationObject.depth = this.depth;
+            return serializationObject;
+        };
+        return RefractionTexture;
+    })(BABYLON.RenderTargetTexture);
+    BABYLON.RefractionTexture = RefractionTexture;
+})(BABYLON || (BABYLON = {}));

+ 334 - 335
src/Materials/Textures/babylon.renderTargetTexture.js

@@ -1,335 +1,334 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var RenderTargetTexture = (function (_super) {
-        __extends(RenderTargetTexture, _super);
-        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
-            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
-            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
-            if (isCube === void 0) { isCube = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.isCube = isCube;
-            /**
-            * Use this list to define the list of mesh you want to render.
-            */
-            this.renderList = new Array();
-            this.renderParticles = true;
-            this.renderSprites = false;
-            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
-            // Events
-            /**
-            * An event triggered when the texture is unbind.
-            * @type {BABYLON.Observable}
-            */
-            this.onAfterUnbindObservable = new BABYLON.Observable();
-            /**
-            * An event triggered before rendering the texture
-            * @type {BABYLON.Observable}
-            */
-            this.onBeforeRenderObservable = new BABYLON.Observable();
-            /**
-            * An event triggered after rendering the texture
-            * @type {BABYLON.Observable}
-            */
-            this.onAfterRenderObservable = new BABYLON.Observable();
-            /**
-            * An event triggered after the texture clear
-            * @type {BABYLON.Observable}
-            */
-            this.onClearObservable = new BABYLON.Observable();
-            this._currentRefreshId = -1;
-            this._refreshRate = 1;
-            this.name = name;
-            this.isRenderTarget = true;
-            this._size = size;
-            this._generateMipMaps = generateMipMaps;
-            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
-            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
-                this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            }
-            if (isCube) {
-                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
-                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
-                this._textureMatrix = BABYLON.Matrix.Identity();
-            }
-            else {
-                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
-            }
-            // Rendering groups
-            this._renderingManager = new BABYLON.RenderingManager(scene);
-        }
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
-            set: function (callback) {
-                if (this._onAfterUnbindObserver) {
-                    this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
-                }
-                this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
-            set: function (callback) {
-                if (this._onBeforeRenderObserver) {
-                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
-                }
-                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
-            set: function (callback) {
-                if (this._onAfterRenderObserver) {
-                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
-                }
-                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
-            set: function (callback) {
-                if (this._onClearObserver) {
-                    this.onClearObservable.remove(this._onClearObserver);
-                }
-                this._onClearObserver = this.onClearObservable.add(callback);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.resetRefreshCounter = function () {
-            this._currentRefreshId = -1;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
-            get: function () {
-                return this._refreshRate;
-            },
-            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
-            set: function (value) {
-                this._refreshRate = value;
-                this.resetRefreshCounter();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype._shouldRender = function () {
-            if (this._currentRefreshId === -1) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            if (this.refreshRate === this._currentRefreshId) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            this._currentRefreshId++;
-            return false;
-        };
-        RenderTargetTexture.prototype.isReady = function () {
-            if (!this.getScene().renderTargetsEnabled) {
-                return false;
-            }
-            return _super.prototype.isReady.call(this);
-        };
-        RenderTargetTexture.prototype.getRenderSize = function () {
-            return this._size;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.scale = function (ratio) {
-            var newSize = this._size * ratio;
-            this.resize(newSize, this._generateMipMaps);
-        };
-        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
-            if (this.isCube) {
-                return this._textureMatrix;
-            }
-            return _super.prototype.getReflectionTextureMatrix.call(this);
-        };
-        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
-            this.releaseInternalTexture();
-            if (this.isCube) {
-                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
-            }
-            else {
-                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
-            }
-        };
-        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            if (this.useCameraPostProcesses !== undefined) {
-                useCameraPostProcess = this.useCameraPostProcesses;
-            }
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
-            }
-            if (this._waitingRenderList) {
-                this.renderList = [];
-                for (var index = 0; index < this._waitingRenderList.length; index++) {
-                    var id = this._waitingRenderList[index];
-                    this.renderList.push(scene.getMeshByID(id));
-                }
-                delete this._waitingRenderList;
-            }
-            // Is predicate defined?
-            if (this.renderListPredicate) {
-                this.renderList.splice(0); // Clear previous renderList
-                var sceneMeshes = this.getScene().meshes;
-                for (var index = 0; index < sceneMeshes.length; index++) {
-                    var mesh = sceneMeshes[index];
-                    if (this.renderListPredicate(mesh)) {
-                        this.renderList.push(mesh);
-                    }
-                }
-            }
-            if (this.renderList && this.renderList.length === 0) {
-                return;
-            }
-            // Prepare renderingManager
-            this._renderingManager.reset();
-            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
-            var sceneRenderId = scene.getRenderId();
-            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
-                var mesh = currentRenderList[meshIndex];
-                if (mesh) {
-                    if (!mesh.isReady()) {
-                        // Reset _currentRefreshId
-                        this.resetRefreshCounter();
-                        continue;
-                    }
-                    mesh._preActivateForIntermediateRendering(sceneRenderId);
-                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
-                        mesh._activate(sceneRenderId);
-                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                            var subMesh = mesh.subMeshes[subIndex];
-                            scene._activeIndices += subMesh.indexCount;
-                            this._renderingManager.dispatch(subMesh);
-                        }
-                    }
-                }
-            }
-            if (this.isCube) {
-                for (var face = 0; face < 6; face++) {
-                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
-                    scene.incrementRenderId();
-                    scene.resetCachedMaterial();
-                }
-            }
-            else {
-                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
-            }
-            this.onAfterUnbindObservable.notifyObservers(this);
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
-            }
-            scene.resetCachedMaterial();
-        };
-        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            // Bind
-            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
-                if (this.isCube) {
-                    engine.bindFramebuffer(this._texture, faceIndex);
-                }
-                else {
-                    engine.bindFramebuffer(this._texture);
-                }
-            }
-            this.onBeforeRenderObservable.notifyObservers(faceIndex);
-            // Clear
-            if (this.onClearObservable.hasObservers()) {
-                this.onClearObservable.notifyObservers(engine);
-            }
-            else {
-                engine.clear(scene.clearColor, true, true);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            // Render
-            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
-            if (useCameraPostProcess) {
-                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            this.onAfterRenderObservable.notifyObservers(faceIndex);
-            // Dump ?
-            if (dumpForDebug) {
-                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
-            }
-            // Unbind
-            if (!this.isCube || faceIndex === 5) {
-                if (this.isCube) {
-                    if (faceIndex === 5) {
-                        engine.generateMipMapsForCubemap(this._texture);
-                    }
-                }
-                engine.unBindFramebuffer(this._texture, this.isCube);
-            }
-        };
-        RenderTargetTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // RenderTarget Texture
-            newTexture.coordinatesMode = this.coordinatesMode;
-            newTexture.renderList = this.renderList.slice(0);
-            return newTexture;
-        };
-        RenderTargetTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.renderTargetSize = this.getRenderSize();
-            serializationObject.renderList = [];
-            for (var index = 0; index < this.renderList.length; index++) {
-                serializationObject.renderList.push(this.renderList[index].id);
-            }
-            return serializationObject;
-        };
-        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
-        return RenderTargetTexture;
-    }(BABYLON.Texture));
-    BABYLON.RenderTargetTexture = RenderTargetTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.renderTargetTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var RenderTargetTexture = (function (_super) {
+        __extends(RenderTargetTexture, _super);
+        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
+            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
+            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
+            if (isCube === void 0) { isCube = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.isCube = isCube;
+            /**
+            * Use this list to define the list of mesh you want to render.
+            */
+            this.renderList = new Array();
+            this.renderParticles = true;
+            this.renderSprites = false;
+            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
+            // Events
+            /**
+            * An event triggered when the texture is unbind.
+            * @type {BABYLON.Observable}
+            */
+            this.onAfterUnbindObservable = new BABYLON.Observable();
+            /**
+            * An event triggered before rendering the texture
+            * @type {BABYLON.Observable}
+            */
+            this.onBeforeRenderObservable = new BABYLON.Observable();
+            /**
+            * An event triggered after rendering the texture
+            * @type {BABYLON.Observable}
+            */
+            this.onAfterRenderObservable = new BABYLON.Observable();
+            /**
+            * An event triggered after the texture clear
+            * @type {BABYLON.Observable}
+            */
+            this.onClearObservable = new BABYLON.Observable();
+            this._currentRefreshId = -1;
+            this._refreshRate = 1;
+            this.name = name;
+            this.isRenderTarget = true;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
+            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
+                this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            }
+            if (isCube) {
+                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
+                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
+                this._textureMatrix = BABYLON.Matrix.Identity();
+            }
+            else {
+                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
+            }
+            // Rendering groups
+            this._renderingManager = new BABYLON.RenderingManager(scene);
+        }
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
+            set: function (callback) {
+                if (this._onAfterUnbindObserver) {
+                    this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
+                }
+                this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
+            set: function (callback) {
+                if (this._onBeforeRenderObserver) {
+                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
+                }
+                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
+            set: function (callback) {
+                if (this._onAfterRenderObserver) {
+                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
+                }
+                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
+            set: function (callback) {
+                if (this._onClearObserver) {
+                    this.onClearObservable.remove(this._onClearObserver);
+                }
+                this._onClearObserver = this.onClearObservable.add(callback);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.resetRefreshCounter = function () {
+            this._currentRefreshId = -1;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
+            get: function () {
+                return this._refreshRate;
+            },
+            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+            set: function (value) {
+                this._refreshRate = value;
+                this.resetRefreshCounter();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype._shouldRender = function () {
+            if (this._currentRefreshId === -1) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            if (this.refreshRate === this._currentRefreshId) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            this._currentRefreshId++;
+            return false;
+        };
+        RenderTargetTexture.prototype.isReady = function () {
+            if (!this.getScene().renderTargetsEnabled) {
+                return false;
+            }
+            return _super.prototype.isReady.call(this);
+        };
+        RenderTargetTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.scale = function (ratio) {
+            var newSize = this._size * ratio;
+            this.resize(newSize, this._generateMipMaps);
+        };
+        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
+            if (this.isCube) {
+                return this._textureMatrix;
+            }
+            return _super.prototype.getReflectionTextureMatrix.call(this);
+        };
+        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
+            this.releaseInternalTexture();
+            if (this.isCube) {
+                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
+            }
+            else {
+                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+            }
+        };
+        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            if (this.useCameraPostProcesses !== undefined) {
+                useCameraPostProcess = this.useCameraPostProcesses;
+            }
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
+            }
+            if (this._waitingRenderList) {
+                this.renderList = [];
+                for (var index = 0; index < this._waitingRenderList.length; index++) {
+                    var id = this._waitingRenderList[index];
+                    this.renderList.push(scene.getMeshByID(id));
+                }
+                delete this._waitingRenderList;
+            }
+            // Is predicate defined?
+            if (this.renderListPredicate) {
+                this.renderList.splice(0); // Clear previous renderList
+                var sceneMeshes = this.getScene().meshes;
+                for (var index = 0; index < sceneMeshes.length; index++) {
+                    var mesh = sceneMeshes[index];
+                    if (this.renderListPredicate(mesh)) {
+                        this.renderList.push(mesh);
+                    }
+                }
+            }
+            if (this.renderList && this.renderList.length === 0) {
+                return;
+            }
+            // Prepare renderingManager
+            this._renderingManager.reset();
+            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
+            var sceneRenderId = scene.getRenderId();
+            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
+                var mesh = currentRenderList[meshIndex];
+                if (mesh) {
+                    if (!mesh.isReady()) {
+                        // Reset _currentRefreshId
+                        this.resetRefreshCounter();
+                        continue;
+                    }
+                    mesh._preActivateForIntermediateRendering(sceneRenderId);
+                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
+                        mesh._activate(sceneRenderId);
+                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                            var subMesh = mesh.subMeshes[subIndex];
+                            scene._activeIndices += subMesh.indexCount;
+                            this._renderingManager.dispatch(subMesh);
+                        }
+                    }
+                }
+            }
+            if (this.isCube) {
+                for (var face = 0; face < 6; face++) {
+                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
+                    scene.incrementRenderId();
+                    scene.resetCachedMaterial();
+                }
+            }
+            else {
+                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
+            }
+            this.onAfterUnbindObservable.notifyObservers(this);
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
+            }
+            scene.resetCachedMaterial();
+        };
+        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            // Bind
+            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
+                if (this.isCube) {
+                    engine.bindFramebuffer(this._texture, faceIndex);
+                }
+                else {
+                    engine.bindFramebuffer(this._texture);
+                }
+            }
+            this.onBeforeRenderObservable.notifyObservers(faceIndex);
+            // Clear
+            if (this.onClearObservable.hasObservers()) {
+                this.onClearObservable.notifyObservers(engine);
+            }
+            else {
+                engine.clear(scene.clearColor, true, true);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            // Render
+            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
+            if (useCameraPostProcess) {
+                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            this.onAfterRenderObservable.notifyObservers(faceIndex);
+            // Dump ?
+            if (dumpForDebug) {
+                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
+            }
+            // Unbind
+            if (!this.isCube || faceIndex === 5) {
+                if (this.isCube) {
+                    if (faceIndex === 5) {
+                        engine.generateMipMapsForCubemap(this._texture);
+                    }
+                }
+                engine.unBindFramebuffer(this._texture, this.isCube);
+            }
+        };
+        RenderTargetTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // RenderTarget Texture
+            newTexture.coordinatesMode = this.coordinatesMode;
+            newTexture.renderList = this.renderList.slice(0);
+            return newTexture;
+        };
+        RenderTargetTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.renderTargetSize = this.getRenderSize();
+            serializationObject.renderList = [];
+            for (var index = 0; index < this.renderList.length; index++) {
+                serializationObject.renderList.push(this.renderList[index].id);
+            }
+            return serializationObject;
+        };
+        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
+        return RenderTargetTexture;
+    })(BABYLON.Texture);
+    BABYLON.RenderTargetTexture = RenderTargetTexture;
+})(BABYLON || (BABYLON = {}));

+ 275 - 276
src/Materials/Textures/babylon.texture.js

@@ -1,276 +1,275 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Texture = (function (_super) {
-        __extends(Texture, _super);
-        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
-            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
-            if (onLoad === void 0) { onLoad = null; }
-            if (onError === void 0) { onError = null; }
-            if (buffer === void 0) { buffer = null; }
-            if (deleteBuffer === void 0) { deleteBuffer = false; }
-            _super.call(this, scene);
-            this.uOffset = 0;
-            this.vOffset = 0;
-            this.uScale = 1.0;
-            this.vScale = 1.0;
-            this.uAng = 0;
-            this.vAng = 0;
-            this.wAng = 0;
-            this.name = url;
-            this.url = url;
-            this._noMipmap = noMipmap;
-            this._invertY = invertY;
-            this._samplingMode = samplingMode;
-            this._buffer = buffer;
-            this._deleteBuffer = deleteBuffer;
-            if (!url) {
-                return;
-            }
-            this._texture = this._getFromCache(url, noMipmap, samplingMode);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
-                    if (deleteBuffer) {
-                        delete this._buffer;
-                    }
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                    this._delayedOnLoad = onLoad;
-                    this._delayedOnError = onError;
-                }
-            }
-            else {
-                BABYLON.Tools.SetImmediate(function () {
-                    if (onLoad) {
-                        onLoad();
-                    }
-                });
-            }
-        }
-        Object.defineProperty(Texture.prototype, "noMipmap", {
-            get: function () {
-                return this._noMipmap;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Texture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
-                if (this._deleteBuffer) {
-                    delete this._buffer;
-                }
-            }
-        };
-        Texture.prototype.updateSamplingMode = function (samplingMode) {
-            if (!this._texture) {
-                return;
-            }
-            this._samplingMode = samplingMode;
-            this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
-        };
-        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
-            x *= this.uScale;
-            y *= this.vScale;
-            x -= 0.5 * this.uScale;
-            y -= 0.5 * this.vScale;
-            z -= 0.5;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
-            t.x += 0.5 * this.uScale + this.uOffset;
-            t.y += 0.5 * this.vScale + this.vOffset;
-            t.z += 0.5;
-        };
-        Texture.prototype.getTextureMatrix = function () {
-            if (this.uOffset === this._cachedUOffset &&
-                this.vOffset === this._cachedVOffset &&
-                this.uScale === this._cachedUScale &&
-                this.vScale === this._cachedVScale &&
-                this.uAng === this._cachedUAng &&
-                this.vAng === this._cachedVAng &&
-                this.wAng === this._cachedWAng) {
-                return this._cachedTextureMatrix;
-            }
-            this._cachedUOffset = this.uOffset;
-            this._cachedVOffset = this.vOffset;
-            this._cachedUScale = this.uScale;
-            this._cachedVScale = this.vScale;
-            this._cachedUAng = this.uAng;
-            this._cachedVAng = this.vAng;
-            this._cachedWAng = this.wAng;
-            if (!this._cachedTextureMatrix) {
-                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
-                this._rowGenerationMatrix = new BABYLON.Matrix();
-                this._t0 = BABYLON.Vector3.Zero();
-                this._t1 = BABYLON.Vector3.Zero();
-                this._t2 = BABYLON.Vector3.Zero();
-            }
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
-            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
-            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
-            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
-            this._t1.subtractInPlace(this._t0);
-            this._t2.subtractInPlace(this._t0);
-            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-            this._cachedTextureMatrix.m[0] = this._t1.x;
-            this._cachedTextureMatrix.m[1] = this._t1.y;
-            this._cachedTextureMatrix.m[2] = this._t1.z;
-            this._cachedTextureMatrix.m[4] = this._t2.x;
-            this._cachedTextureMatrix.m[5] = this._t2.y;
-            this._cachedTextureMatrix.m[6] = this._t2.z;
-            this._cachedTextureMatrix.m[8] = this._t0.x;
-            this._cachedTextureMatrix.m[9] = this._t0.y;
-            this._cachedTextureMatrix.m[10] = this._t0.z;
-            return this._cachedTextureMatrix;
-        };
-        Texture.prototype.getReflectionTextureMatrix = function () {
-            if (this.uOffset === this._cachedUOffset &&
-                this.vOffset === this._cachedVOffset &&
-                this.uScale === this._cachedUScale &&
-                this.vScale === this._cachedVScale &&
-                this.coordinatesMode === this._cachedCoordinatesMode) {
-                return this._cachedTextureMatrix;
-            }
-            if (!this._cachedTextureMatrix) {
-                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
-                this._projectionModeMatrix = BABYLON.Matrix.Zero();
-            }
-            this._cachedCoordinatesMode = this.coordinatesMode;
-            switch (this.coordinatesMode) {
-                case Texture.PLANAR_MODE:
-                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                    this._cachedTextureMatrix[0] = this.uScale;
-                    this._cachedTextureMatrix[5] = this.vScale;
-                    this._cachedTextureMatrix[12] = this.uOffset;
-                    this._cachedTextureMatrix[13] = this.vOffset;
-                    break;
-                case Texture.PROJECTION_MODE:
-                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
-                    this._projectionModeMatrix.m[0] = 0.5;
-                    this._projectionModeMatrix.m[5] = -0.5;
-                    this._projectionModeMatrix.m[10] = 0.0;
-                    this._projectionModeMatrix.m[12] = 0.5;
-                    this._projectionModeMatrix.m[13] = 0.5;
-                    this._projectionModeMatrix.m[14] = 1.0;
-                    this._projectionModeMatrix.m[15] = 1.0;
-                    this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
-                    break;
-                default:
-                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                    break;
-            }
-            return this._cachedTextureMatrix;
-        };
-        Texture.prototype.clone = function () {
-            var _this = this;
-            return BABYLON.SerializationHelper.Clone(function () {
-                return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
-            }, this);
-        };
-        // Statics
-        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
-            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
-            if (onLoad === void 0) { onLoad = null; }
-            if (onError === void 0) { onError = null; }
-            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
-        };
-        Texture.Parse = function (parsedTexture, scene, rootUrl) {
-            if (parsedTexture.isCube) {
-                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
-            }
-            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
-                return null;
-            }
-            var texture = BABYLON.SerializationHelper.Parse(function () {
-                if (parsedTexture.mirrorPlane) {
-                    var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                    mirrorTexture._waitingRenderList = parsedTexture.renderList;
-                    mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
-                    return mirrorTexture;
-                }
-                else if (parsedTexture.isRenderTarget) {
-                    var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                    renderTargetTexture._waitingRenderList = parsedTexture.renderList;
-                    return renderTargetTexture;
-                }
-                else {
-                    var texture;
-                    if (parsedTexture.base64String) {
-                        texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
-                    }
-                    else {
-                        texture = new Texture(rootUrl + parsedTexture.name, scene);
-                    }
-                    return texture;
-                }
-            }, parsedTexture, scene);
-            // Animations
-            if (parsedTexture.animations) {
-                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedTexture.animations[animationIndex];
-                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                }
-            }
-            return texture;
-        };
-        // Constants
-        Texture.NEAREST_SAMPLINGMODE = 1;
-        Texture.BILINEAR_SAMPLINGMODE = 2;
-        Texture.TRILINEAR_SAMPLINGMODE = 3;
-        Texture.EXPLICIT_MODE = 0;
-        Texture.SPHERICAL_MODE = 1;
-        Texture.PLANAR_MODE = 2;
-        Texture.CUBIC_MODE = 3;
-        Texture.PROJECTION_MODE = 4;
-        Texture.SKYBOX_MODE = 5;
-        Texture.INVCUBIC_MODE = 6;
-        Texture.EQUIRECTANGULAR_MODE = 7;
-        Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
-        Texture.CLAMP_ADDRESSMODE = 0;
-        Texture.WRAP_ADDRESSMODE = 1;
-        Texture.MIRROR_ADDRESSMODE = 2;
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "url", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "uOffset", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "vOffset", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "uScale", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "vScale", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "uAng", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "vAng", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Texture.prototype, "wAng", void 0);
-        return Texture;
-    }(BABYLON.BaseTexture));
-    BABYLON.Texture = Texture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.texture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Texture = (function (_super) {
+        __extends(Texture, _super);
+        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
+            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
+            if (onLoad === void 0) { onLoad = null; }
+            if (onError === void 0) { onError = null; }
+            if (buffer === void 0) { buffer = null; }
+            if (deleteBuffer === void 0) { deleteBuffer = false; }
+            _super.call(this, scene);
+            this.uOffset = 0;
+            this.vOffset = 0;
+            this.uScale = 1.0;
+            this.vScale = 1.0;
+            this.uAng = 0;
+            this.vAng = 0;
+            this.wAng = 0;
+            this.name = url;
+            this.url = url;
+            this._noMipmap = noMipmap;
+            this._invertY = invertY;
+            this._samplingMode = samplingMode;
+            this._buffer = buffer;
+            this._deleteBuffer = deleteBuffer;
+            if (!url) {
+                return;
+            }
+            this._texture = this._getFromCache(url, noMipmap, samplingMode);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
+                    if (deleteBuffer) {
+                        delete this._buffer;
+                    }
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                    this._delayedOnLoad = onLoad;
+                    this._delayedOnError = onError;
+                }
+            }
+            else {
+                BABYLON.Tools.SetImmediate(function () {
+                    if (onLoad) {
+                        onLoad();
+                    }
+                });
+            }
+        }
+        Object.defineProperty(Texture.prototype, "noMipmap", {
+            get: function () {
+                return this._noMipmap;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Texture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
+                if (this._deleteBuffer) {
+                    delete this._buffer;
+                }
+            }
+        };
+        Texture.prototype.updateSamplingMode = function (samplingMode) {
+            if (!this._texture) {
+                return;
+            }
+            this._samplingMode = samplingMode;
+            this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
+        };
+        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
+            x *= this.uScale;
+            y *= this.vScale;
+            x -= 0.5 * this.uScale;
+            y -= 0.5 * this.vScale;
+            z -= 0.5;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
+            t.x += 0.5 * this.uScale + this.uOffset;
+            t.y += 0.5 * this.vScale + this.vOffset;
+            t.z += 0.5;
+        };
+        Texture.prototype.getTextureMatrix = function () {
+            if (this.uOffset === this._cachedUOffset &&
+                this.vOffset === this._cachedVOffset &&
+                this.uScale === this._cachedUScale &&
+                this.vScale === this._cachedVScale &&
+                this.uAng === this._cachedUAng &&
+                this.vAng === this._cachedVAng &&
+                this.wAng === this._cachedWAng) {
+                return this._cachedTextureMatrix;
+            }
+            this._cachedUOffset = this.uOffset;
+            this._cachedVOffset = this.vOffset;
+            this._cachedUScale = this.uScale;
+            this._cachedVScale = this.vScale;
+            this._cachedUAng = this.uAng;
+            this._cachedVAng = this.vAng;
+            this._cachedWAng = this.wAng;
+            if (!this._cachedTextureMatrix) {
+                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
+                this._rowGenerationMatrix = new BABYLON.Matrix();
+                this._t0 = BABYLON.Vector3.Zero();
+                this._t1 = BABYLON.Vector3.Zero();
+                this._t2 = BABYLON.Vector3.Zero();
+            }
+            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
+            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
+            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
+            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
+            this._t1.subtractInPlace(this._t0);
+            this._t2.subtractInPlace(this._t0);
+            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+            this._cachedTextureMatrix.m[0] = this._t1.x;
+            this._cachedTextureMatrix.m[1] = this._t1.y;
+            this._cachedTextureMatrix.m[2] = this._t1.z;
+            this._cachedTextureMatrix.m[4] = this._t2.x;
+            this._cachedTextureMatrix.m[5] = this._t2.y;
+            this._cachedTextureMatrix.m[6] = this._t2.z;
+            this._cachedTextureMatrix.m[8] = this._t0.x;
+            this._cachedTextureMatrix.m[9] = this._t0.y;
+            this._cachedTextureMatrix.m[10] = this._t0.z;
+            return this._cachedTextureMatrix;
+        };
+        Texture.prototype.getReflectionTextureMatrix = function () {
+            if (this.uOffset === this._cachedUOffset &&
+                this.vOffset === this._cachedVOffset &&
+                this.uScale === this._cachedUScale &&
+                this.vScale === this._cachedVScale &&
+                this.coordinatesMode === this._cachedCoordinatesMode) {
+                return this._cachedTextureMatrix;
+            }
+            if (!this._cachedTextureMatrix) {
+                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
+                this._projectionModeMatrix = BABYLON.Matrix.Zero();
+            }
+            this._cachedCoordinatesMode = this.coordinatesMode;
+            switch (this.coordinatesMode) {
+                case Texture.PLANAR_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    this._cachedTextureMatrix[0] = this.uScale;
+                    this._cachedTextureMatrix[5] = this.vScale;
+                    this._cachedTextureMatrix[12] = this.uOffset;
+                    this._cachedTextureMatrix[13] = this.vOffset;
+                    break;
+                case Texture.PROJECTION_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
+                    this._projectionModeMatrix.m[0] = 0.5;
+                    this._projectionModeMatrix.m[5] = -0.5;
+                    this._projectionModeMatrix.m[10] = 0.0;
+                    this._projectionModeMatrix.m[12] = 0.5;
+                    this._projectionModeMatrix.m[13] = 0.5;
+                    this._projectionModeMatrix.m[14] = 1.0;
+                    this._projectionModeMatrix.m[15] = 1.0;
+                    this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
+                    break;
+                default:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    break;
+            }
+            return this._cachedTextureMatrix;
+        };
+        Texture.prototype.clone = function () {
+            var _this = this;
+            return BABYLON.SerializationHelper.Clone(function () {
+                return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
+            }, this);
+        };
+        // Statics
+        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
+            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
+            if (onLoad === void 0) { onLoad = null; }
+            if (onError === void 0) { onError = null; }
+            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
+        };
+        Texture.Parse = function (parsedTexture, scene, rootUrl) {
+            if (parsedTexture.isCube) {
+                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
+            }
+            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
+                return null;
+            }
+            var texture = BABYLON.SerializationHelper.Parse(function () {
+                if (parsedTexture.mirrorPlane) {
+                    var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
+                    mirrorTexture._waitingRenderList = parsedTexture.renderList;
+                    mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
+                    return mirrorTexture;
+                }
+                else if (parsedTexture.isRenderTarget) {
+                    var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
+                    renderTargetTexture._waitingRenderList = parsedTexture.renderList;
+                    return renderTargetTexture;
+                }
+                else {
+                    var texture;
+                    if (parsedTexture.base64String) {
+                        texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
+                    }
+                    else {
+                        texture = new Texture(rootUrl + parsedTexture.name, scene);
+                    }
+                    return texture;
+                }
+            }, parsedTexture, scene);
+            // Animations
+            if (parsedTexture.animations) {
+                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedTexture.animations[animationIndex];
+                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                }
+            }
+            return texture;
+        };
+        // Constants
+        Texture.NEAREST_SAMPLINGMODE = 1;
+        Texture.BILINEAR_SAMPLINGMODE = 2;
+        Texture.TRILINEAR_SAMPLINGMODE = 3;
+        Texture.EXPLICIT_MODE = 0;
+        Texture.SPHERICAL_MODE = 1;
+        Texture.PLANAR_MODE = 2;
+        Texture.CUBIC_MODE = 3;
+        Texture.PROJECTION_MODE = 4;
+        Texture.SKYBOX_MODE = 5;
+        Texture.INVCUBIC_MODE = 6;
+        Texture.EQUIRECTANGULAR_MODE = 7;
+        Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
+        Texture.CLAMP_ADDRESSMODE = 0;
+        Texture.WRAP_ADDRESSMODE = 1;
+        Texture.MIRROR_ADDRESSMODE = 2;
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "url", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "uOffset", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "vOffset", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "uScale", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "vScale", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "uAng", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "vAng", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Texture.prototype, "wAng", void 0);
+        return Texture;
+    })(BABYLON.BaseTexture);
+    BABYLON.Texture = Texture;
+})(BABYLON || (BABYLON = {}));

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 545 - 546
src/Materials/babylon.colorCurves.js


+ 470 - 471
src/Materials/babylon.effect.js

@@ -1,471 +1,470 @@
-var BABYLON;
-(function (BABYLON) {
-    var EffectFallbacks = (function () {
-        function EffectFallbacks() {
-            this._defines = {};
-            this._currentRank = 32;
-            this._maxRank = -1;
-        }
-        EffectFallbacks.prototype.addFallback = function (rank, define) {
-            if (!this._defines[rank]) {
-                if (rank < this._currentRank) {
-                    this._currentRank = rank;
-                }
-                if (rank > this._maxRank) {
-                    this._maxRank = rank;
-                }
-                this._defines[rank] = new Array();
-            }
-            this._defines[rank].push(define);
-        };
-        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
-            this._meshRank = rank;
-            this._mesh = mesh;
-            if (rank > this._maxRank) {
-                this._maxRank = rank;
-            }
-        };
-        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
-            get: function () {
-                return this._currentRank <= this._maxRank;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        EffectFallbacks.prototype.reduce = function (currentDefines) {
-            var currentFallbacks = this._defines[this._currentRank];
-            for (var index = 0; index < currentFallbacks.length; index++) {
-                currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
-            }
-            if (this._mesh && this._currentRank === this._meshRank) {
-                this._mesh.computeBonesUsingShaders = false;
-                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
-                BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
-            }
-            this._currentRank++;
-            return currentDefines;
-        };
-        return EffectFallbacks;
-    }());
-    BABYLON.EffectFallbacks = EffectFallbacks;
-    var Effect = (function () {
-        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
-            var _this = this;
-            this._isReady = false;
-            this._compilationError = "";
-            this._valueCache = [];
-            this._engine = engine;
-            this.name = baseName;
-            this.defines = defines;
-            this._uniformsNames = uniformsNames.concat(samplers);
-            this._samplers = samplers;
-            this._attributesNames = attributesNames;
-            this.onError = onError;
-            this.onCompiled = onCompiled;
-            this._indexParameters = indexParameters;
-            var vertexSource;
-            var fragmentSource;
-            if (baseName.vertexElement) {
-                vertexSource = document.getElementById(baseName.vertexElement);
-                if (!vertexSource) {
-                    vertexSource = baseName.vertexElement;
-                }
-            }
-            else {
-                vertexSource = baseName.vertex || baseName;
-            }
-            if (baseName.fragmentElement) {
-                fragmentSource = document.getElementById(baseName.fragmentElement);
-                if (!fragmentSource) {
-                    fragmentSource = baseName.fragmentElement;
-                }
-            }
-            else {
-                fragmentSource = baseName.fragment || baseName;
-            }
-            this._loadVertexShader(vertexSource, function (vertexCode) {
-                _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
-                    _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
-                        _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
-                            _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
-                        });
-                    });
-                });
-            });
-        }
-        // Properties
-        Effect.prototype.isReady = function () {
-            return this._isReady;
-        };
-        Effect.prototype.getProgram = function () {
-            return this._program;
-        };
-        Effect.prototype.getAttributesNames = function () {
-            return this._attributesNames;
-        };
-        Effect.prototype.getAttributeLocation = function (index) {
-            return this._attributes[index];
-        };
-        Effect.prototype.getAttributeLocationByName = function (name) {
-            var index = this._attributesNames.indexOf(name);
-            return this._attributes[index];
-        };
-        Effect.prototype.getAttributesCount = function () {
-            return this._attributes.length;
-        };
-        Effect.prototype.getUniformIndex = function (uniformName) {
-            return this._uniformsNames.indexOf(uniformName);
-        };
-        Effect.prototype.getUniform = function (uniformName) {
-            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
-        };
-        Effect.prototype.getSamplers = function () {
-            return this._samplers;
-        };
-        Effect.prototype.getCompilationError = function () {
-            return this._compilationError;
-        };
-        // Methods
-        Effect.prototype._loadVertexShader = function (vertex, callback) {
-            // DOM element ?
-            if (vertex instanceof HTMLElement) {
-                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
-                callback(vertexCode);
-                return;
-            }
-            // Is in local store ?
-            if (Effect.ShadersStore[vertex + "VertexShader"]) {
-                callback(Effect.ShadersStore[vertex + "VertexShader"]);
-                return;
-            }
-            var vertexShaderUrl;
-            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
-                vertexShaderUrl = vertex;
-            }
-            else {
-                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
-            }
-            // Vertex shader
-            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
-        };
-        Effect.prototype._loadFragmentShader = function (fragment, callback) {
-            // DOM element ?
-            if (fragment instanceof HTMLElement) {
-                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
-                callback(fragmentCode);
-                return;
-            }
-            // Is in local store ?
-            if (Effect.ShadersStore[fragment + "PixelShader"]) {
-                callback(Effect.ShadersStore[fragment + "PixelShader"]);
-                return;
-            }
-            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
-                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
-                return;
-            }
-            var fragmentShaderUrl;
-            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
-                fragmentShaderUrl = fragment;
-            }
-            else {
-                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
-            }
-            // Fragment shader
-            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
-        };
-        Effect.prototype._dumpShadersName = function () {
-            if (this.name.vertexElement) {
-                BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
-                BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
-            }
-            else if (this.name.vertex) {
-                BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
-                BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
-            }
-            else {
-                BABYLON.Tools.Error("Vertex shader:" + this.name);
-                BABYLON.Tools.Error("Fragment shader:" + this.name);
-            }
-        };
-        Effect.prototype._processIncludes = function (sourceCode, callback) {
-            var _this = this;
-            var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
-            var match = regex.exec(sourceCode);
-            var returnValue = new String(sourceCode);
-            while (match != null) {
-                var includeFile = match[1];
-                if (Effect.IncludesShadersStore[includeFile]) {
-                    // Substitution
-                    var includeContent = Effect.IncludesShadersStore[includeFile];
-                    if (match[2]) {
-                        var splits = match[3].split(",");
-                        for (var index = 0; index < splits.length; index += 2) {
-                            var source = new RegExp(splits[index], "g");
-                            var dest = splits[index + 1];
-                            includeContent = includeContent.replace(source, dest);
-                        }
-                    }
-                    if (match[4]) {
-                        var indexString = match[5];
-                        if (indexString.indexOf("..") !== -1) {
-                            var indexSplits = indexString.split("..");
-                            var minIndex = parseInt(indexSplits[0]);
-                            var maxIndex = parseInt(indexSplits[1]);
-                            var sourceIncludeContent = includeContent.slice(0);
-                            includeContent = "";
-                            if (isNaN(maxIndex)) {
-                                maxIndex = this._indexParameters[indexSplits[1]];
-                            }
-                            for (var i = minIndex; i <= maxIndex; i++) {
-                                includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
-                            }
-                        }
-                        else {
-                            includeContent = includeContent.replace(/\{X\}/g, indexString);
-                        }
-                    }
-                    // Replace
-                    returnValue = returnValue.replace(match[0], includeContent);
-                }
-                else {
-                    var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
-                    BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
-                        Effect.IncludesShadersStore[includeFile] = fileContent;
-                        _this._processIncludes(returnValue, callback);
-                    });
-                    return;
-                }
-                match = regex.exec(sourceCode);
-            }
-            callback(returnValue);
-        };
-        Effect.prototype._processPrecision = function (source) {
-            if (source.indexOf("precision highp float") === -1) {
-                if (!this._engine.getCaps().highPrecisionShaderSupported) {
-                    source = "precision mediump float;\n" + source;
-                }
-                else {
-                    source = "precision highp float;\n" + source;
-                }
-            }
-            else {
-                if (!this._engine.getCaps().highPrecisionShaderSupported) {
-                    source = source.replace("precision highp float", "precision mediump float");
-                }
-            }
-            return source;
-        };
-        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
-            try {
-                var engine = this._engine;
-                // Precision
-                vertexSourceCode = this._processPrecision(vertexSourceCode);
-                fragmentSourceCode = this._processPrecision(fragmentSourceCode);
-                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
-                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
-                this._attributes = engine.getAttributes(this._program, attributesNames);
-                for (var index = 0; index < this._samplers.length; index++) {
-                    var sampler = this.getUniform(this._samplers[index]);
-                    if (sampler == null) {
-                        this._samplers.splice(index, 1);
-                        index--;
-                    }
-                }
-                engine.bindSamplers(this);
-                this._isReady = true;
-                if (this.onCompiled) {
-                    this.onCompiled(this);
-                }
-            }
-            catch (e) {
-                // Is it a problem with precision?
-                if (e.message.indexOf("highp") !== -1) {
-                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
-                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
-                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
-                    return;
-                }
-                // Let's go through fallbacks then
-                if (fallbacks && fallbacks.isMoreFallbacks) {
-                    BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
-                    this._dumpShadersName();
-                    defines = fallbacks.reduce(defines);
-                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
-                }
-                else {
-                    BABYLON.Tools.Error("Unable to compile effect: ");
-                    this._dumpShadersName();
-                    BABYLON.Tools.Error("Defines: " + defines);
-                    BABYLON.Tools.Error("Error: " + e.message);
-                    this._compilationError = e.message;
-                    if (this.onError) {
-                        this.onError(this, this._compilationError);
-                    }
-                }
-            }
-        };
-        Object.defineProperty(Effect.prototype, "isSupported", {
-            get: function () {
-                return this._compilationError === "";
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Effect.prototype._bindTexture = function (channel, texture) {
-            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
-        };
-        Effect.prototype.setTexture = function (channel, texture) {
-            this._engine.setTexture(this._samplers.indexOf(channel), texture);
-        };
-        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
-            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
-        };
-        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = new BABYLON.Matrix();
-            }
-            for (var index = 0; index < 16; index++) {
-                this._valueCache[uniformName].m[index] = matrix.m[index];
-            }
-        };
-        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-        };
-        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y, z];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-            this._valueCache[uniformName][2] = z;
-        };
-        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y, z, w];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-            this._valueCache[uniformName][2] = z;
-            this._valueCache[uniformName][3] = w;
-        };
-        Effect.prototype.setArray = function (uniformName, array) {
-            this._engine.setArray(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray2 = function (uniformName, array) {
-            this._engine.setArray2(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray3 = function (uniformName, array) {
-            this._engine.setArray3(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray4 = function (uniformName, array) {
-            this._engine.setArray4(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setMatrices = function (uniformName, matrices) {
-            this._engine.setMatrices(this.getUniform(uniformName), matrices);
-            return this;
-        };
-        Effect.prototype.setMatrix = function (uniformName, matrix) {
-            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
-            //    return this;
-            // this._cacheMatrix(uniformName, matrix);
-            this._engine.setMatrix(this.getUniform(uniformName), matrix);
-            return this;
-        };
-        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
-            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
-            return this;
-        };
-        Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
-            this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
-            return this;
-        };
-        Effect.prototype.setFloat = function (uniformName, value) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
-                return this;
-            this._valueCache[uniformName] = value;
-            this._engine.setFloat(this.getUniform(uniformName), value);
-            return this;
-        };
-        Effect.prototype.setBool = function (uniformName, bool) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
-                return this;
-            this._valueCache[uniformName] = bool;
-            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
-            return this;
-        };
-        Effect.prototype.setVector2 = function (uniformName, vector2) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
-                return this;
-            this._cacheFloat2(uniformName, vector2.x, vector2.y);
-            this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
-            return this;
-        };
-        Effect.prototype.setFloat2 = function (uniformName, x, y) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
-                return this;
-            this._cacheFloat2(uniformName, x, y);
-            this._engine.setFloat2(this.getUniform(uniformName), x, y);
-            return this;
-        };
-        Effect.prototype.setVector3 = function (uniformName, vector3) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
-                return this;
-            this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
-            this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
-            return this;
-        };
-        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
-                return this;
-            this._cacheFloat3(uniformName, x, y, z);
-            this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
-            return this;
-        };
-        Effect.prototype.setVector4 = function (uniformName, vector4) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
-                return this;
-            this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
-            this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
-            return this;
-        };
-        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
-                return this;
-            this._cacheFloat4(uniformName, x, y, z, w);
-            this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
-            return this;
-        };
-        Effect.prototype.setColor3 = function (uniformName, color3) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
-                return this;
-            this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
-            this._engine.setColor3(this.getUniform(uniformName), color3);
-            return this;
-        };
-        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
-                return this;
-            this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
-            this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
-            return this;
-        };
-        // Statics
-        Effect.ShadersStore = {};
-        Effect.IncludesShadersStore = {};
-        return Effect;
-    }());
-    BABYLON.Effect = Effect;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.effect.js.map
+var BABYLON;
+(function (BABYLON) {
+    var EffectFallbacks = (function () {
+        function EffectFallbacks() {
+            this._defines = {};
+            this._currentRank = 32;
+            this._maxRank = -1;
+        }
+        EffectFallbacks.prototype.addFallback = function (rank, define) {
+            if (!this._defines[rank]) {
+                if (rank < this._currentRank) {
+                    this._currentRank = rank;
+                }
+                if (rank > this._maxRank) {
+                    this._maxRank = rank;
+                }
+                this._defines[rank] = new Array();
+            }
+            this._defines[rank].push(define);
+        };
+        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
+            this._meshRank = rank;
+            this._mesh = mesh;
+            if (rank > this._maxRank) {
+                this._maxRank = rank;
+            }
+        };
+        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
+            get: function () {
+                return this._currentRank <= this._maxRank;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        EffectFallbacks.prototype.reduce = function (currentDefines) {
+            var currentFallbacks = this._defines[this._currentRank];
+            for (var index = 0; index < currentFallbacks.length; index++) {
+                currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
+            }
+            if (this._mesh && this._currentRank === this._meshRank) {
+                this._mesh.computeBonesUsingShaders = false;
+                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
+                BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
+            }
+            this._currentRank++;
+            return currentDefines;
+        };
+        return EffectFallbacks;
+    })();
+    BABYLON.EffectFallbacks = EffectFallbacks;
+    var Effect = (function () {
+        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
+            var _this = this;
+            this._isReady = false;
+            this._compilationError = "";
+            this._valueCache = [];
+            this._engine = engine;
+            this.name = baseName;
+            this.defines = defines;
+            this._uniformsNames = uniformsNames.concat(samplers);
+            this._samplers = samplers;
+            this._attributesNames = attributesNames;
+            this.onError = onError;
+            this.onCompiled = onCompiled;
+            this._indexParameters = indexParameters;
+            var vertexSource;
+            var fragmentSource;
+            if (baseName.vertexElement) {
+                vertexSource = document.getElementById(baseName.vertexElement);
+                if (!vertexSource) {
+                    vertexSource = baseName.vertexElement;
+                }
+            }
+            else {
+                vertexSource = baseName.vertex || baseName;
+            }
+            if (baseName.fragmentElement) {
+                fragmentSource = document.getElementById(baseName.fragmentElement);
+                if (!fragmentSource) {
+                    fragmentSource = baseName.fragmentElement;
+                }
+            }
+            else {
+                fragmentSource = baseName.fragment || baseName;
+            }
+            this._loadVertexShader(vertexSource, function (vertexCode) {
+                _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
+                    _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
+                        _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
+                            _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
+                        });
+                    });
+                });
+            });
+        }
+        // Properties
+        Effect.prototype.isReady = function () {
+            return this._isReady;
+        };
+        Effect.prototype.getProgram = function () {
+            return this._program;
+        };
+        Effect.prototype.getAttributesNames = function () {
+            return this._attributesNames;
+        };
+        Effect.prototype.getAttributeLocation = function (index) {
+            return this._attributes[index];
+        };
+        Effect.prototype.getAttributeLocationByName = function (name) {
+            var index = this._attributesNames.indexOf(name);
+            return this._attributes[index];
+        };
+        Effect.prototype.getAttributesCount = function () {
+            return this._attributes.length;
+        };
+        Effect.prototype.getUniformIndex = function (uniformName) {
+            return this._uniformsNames.indexOf(uniformName);
+        };
+        Effect.prototype.getUniform = function (uniformName) {
+            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
+        };
+        Effect.prototype.getSamplers = function () {
+            return this._samplers;
+        };
+        Effect.prototype.getCompilationError = function () {
+            return this._compilationError;
+        };
+        // Methods
+        Effect.prototype._loadVertexShader = function (vertex, callback) {
+            // DOM element ?
+            if (vertex instanceof HTMLElement) {
+                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
+                callback(vertexCode);
+                return;
+            }
+            // Is in local store ?
+            if (Effect.ShadersStore[vertex + "VertexShader"]) {
+                callback(Effect.ShadersStore[vertex + "VertexShader"]);
+                return;
+            }
+            var vertexShaderUrl;
+            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
+                vertexShaderUrl = vertex;
+            }
+            else {
+                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
+            }
+            // Vertex shader
+            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
+        };
+        Effect.prototype._loadFragmentShader = function (fragment, callback) {
+            // DOM element ?
+            if (fragment instanceof HTMLElement) {
+                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
+                callback(fragmentCode);
+                return;
+            }
+            // Is in local store ?
+            if (Effect.ShadersStore[fragment + "PixelShader"]) {
+                callback(Effect.ShadersStore[fragment + "PixelShader"]);
+                return;
+            }
+            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
+                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
+                return;
+            }
+            var fragmentShaderUrl;
+            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
+                fragmentShaderUrl = fragment;
+            }
+            else {
+                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
+            }
+            // Fragment shader
+            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
+        };
+        Effect.prototype._dumpShadersName = function () {
+            if (this.name.vertexElement) {
+                BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
+                BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
+            }
+            else if (this.name.vertex) {
+                BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
+                BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
+            }
+            else {
+                BABYLON.Tools.Error("Vertex shader:" + this.name);
+                BABYLON.Tools.Error("Fragment shader:" + this.name);
+            }
+        };
+        Effect.prototype._processIncludes = function (sourceCode, callback) {
+            var _this = this;
+            var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
+            var match = regex.exec(sourceCode);
+            var returnValue = new String(sourceCode);
+            while (match != null) {
+                var includeFile = match[1];
+                if (Effect.IncludesShadersStore[includeFile]) {
+                    // Substitution
+                    var includeContent = Effect.IncludesShadersStore[includeFile];
+                    if (match[2]) {
+                        var splits = match[3].split(",");
+                        for (var index = 0; index < splits.length; index += 2) {
+                            var source = new RegExp(splits[index], "g");
+                            var dest = splits[index + 1];
+                            includeContent = includeContent.replace(source, dest);
+                        }
+                    }
+                    if (match[4]) {
+                        var indexString = match[5];
+                        if (indexString.indexOf("..") !== -1) {
+                            var indexSplits = indexString.split("..");
+                            var minIndex = parseInt(indexSplits[0]);
+                            var maxIndex = parseInt(indexSplits[1]);
+                            var sourceIncludeContent = includeContent.slice(0);
+                            includeContent = "";
+                            if (isNaN(maxIndex)) {
+                                maxIndex = this._indexParameters[indexSplits[1]];
+                            }
+                            for (var i = minIndex; i <= maxIndex; i++) {
+                                includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
+                            }
+                        }
+                        else {
+                            includeContent = includeContent.replace(/\{X\}/g, indexString);
+                        }
+                    }
+                    // Replace
+                    returnValue = returnValue.replace(match[0], includeContent);
+                }
+                else {
+                    var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
+                    BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
+                        Effect.IncludesShadersStore[includeFile] = fileContent;
+                        _this._processIncludes(returnValue, callback);
+                    });
+                    return;
+                }
+                match = regex.exec(sourceCode);
+            }
+            callback(returnValue);
+        };
+        Effect.prototype._processPrecision = function (source) {
+            if (source.indexOf("precision highp float") === -1) {
+                if (!this._engine.getCaps().highPrecisionShaderSupported) {
+                    source = "precision mediump float;\n" + source;
+                }
+                else {
+                    source = "precision highp float;\n" + source;
+                }
+            }
+            else {
+                if (!this._engine.getCaps().highPrecisionShaderSupported) {
+                    source = source.replace("precision highp float", "precision mediump float");
+                }
+            }
+            return source;
+        };
+        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
+            try {
+                var engine = this._engine;
+                // Precision
+                vertexSourceCode = this._processPrecision(vertexSourceCode);
+                fragmentSourceCode = this._processPrecision(fragmentSourceCode);
+                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
+                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
+                this._attributes = engine.getAttributes(this._program, attributesNames);
+                for (var index = 0; index < this._samplers.length; index++) {
+                    var sampler = this.getUniform(this._samplers[index]);
+                    if (sampler == null) {
+                        this._samplers.splice(index, 1);
+                        index--;
+                    }
+                }
+                engine.bindSamplers(this);
+                this._isReady = true;
+                if (this.onCompiled) {
+                    this.onCompiled(this);
+                }
+            }
+            catch (e) {
+                // Is it a problem with precision?
+                if (e.message.indexOf("highp") !== -1) {
+                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
+                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
+                    return;
+                }
+                // Let's go through fallbacks then
+                if (fallbacks && fallbacks.isMoreFallbacks) {
+                    BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
+                    this._dumpShadersName();
+                    defines = fallbacks.reduce(defines);
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
+                }
+                else {
+                    BABYLON.Tools.Error("Unable to compile effect: ");
+                    this._dumpShadersName();
+                    BABYLON.Tools.Error("Defines: " + defines);
+                    BABYLON.Tools.Error("Error: " + e.message);
+                    this._compilationError = e.message;
+                    if (this.onError) {
+                        this.onError(this, this._compilationError);
+                    }
+                }
+            }
+        };
+        Object.defineProperty(Effect.prototype, "isSupported", {
+            get: function () {
+                return this._compilationError === "";
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Effect.prototype._bindTexture = function (channel, texture) {
+            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
+        };
+        Effect.prototype.setTexture = function (channel, texture) {
+            this._engine.setTexture(this._samplers.indexOf(channel), texture);
+        };
+        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
+            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
+        };
+        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = new BABYLON.Matrix();
+            }
+            for (var index = 0; index < 16; index++) {
+                this._valueCache[uniformName].m[index] = matrix.m[index];
+            }
+        };
+        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+        };
+        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y, z];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+        };
+        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y, z, w];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+            this._valueCache[uniformName][3] = w;
+        };
+        Effect.prototype.setArray = function (uniformName, array) {
+            this._engine.setArray(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray2 = function (uniformName, array) {
+            this._engine.setArray2(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray3 = function (uniformName, array) {
+            this._engine.setArray3(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray4 = function (uniformName, array) {
+            this._engine.setArray4(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setMatrices = function (uniformName, matrices) {
+            this._engine.setMatrices(this.getUniform(uniformName), matrices);
+            return this;
+        };
+        Effect.prototype.setMatrix = function (uniformName, matrix) {
+            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
+            //    return this;
+            // this._cacheMatrix(uniformName, matrix);
+            this._engine.setMatrix(this.getUniform(uniformName), matrix);
+            return this;
+        };
+        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
+            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
+            return this;
+        };
+        Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
+            this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
+            return this;
+        };
+        Effect.prototype.setFloat = function (uniformName, value) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
+                return this;
+            this._valueCache[uniformName] = value;
+            this._engine.setFloat(this.getUniform(uniformName), value);
+            return this;
+        };
+        Effect.prototype.setBool = function (uniformName, bool) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
+                return this;
+            this._valueCache[uniformName] = bool;
+            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
+            return this;
+        };
+        Effect.prototype.setVector2 = function (uniformName, vector2) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
+                return this;
+            this._cacheFloat2(uniformName, vector2.x, vector2.y);
+            this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
+            return this;
+        };
+        Effect.prototype.setFloat2 = function (uniformName, x, y) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
+                return this;
+            this._cacheFloat2(uniformName, x, y);
+            this._engine.setFloat2(this.getUniform(uniformName), x, y);
+            return this;
+        };
+        Effect.prototype.setVector3 = function (uniformName, vector3) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
+                return this;
+            this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
+            this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
+            return this;
+        };
+        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
+                return this;
+            this._cacheFloat3(uniformName, x, y, z);
+            this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
+            return this;
+        };
+        Effect.prototype.setVector4 = function (uniformName, vector4) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
+                return this;
+            this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
+            this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
+            return this;
+        };
+        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
+                return this;
+            this._cacheFloat4(uniformName, x, y, z, w);
+            this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
+            return this;
+        };
+        Effect.prototype.setColor3 = function (uniformName, color3) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
+                return this;
+            this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
+            this._engine.setColor3(this.getUniform(uniformName), color3);
+            return this;
+        };
+        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
+                return this;
+            this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
+            this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
+            return this;
+        };
+        // Statics
+        Effect.ShadersStore = {};
+        Effect.IncludesShadersStore = {};
+        return Effect;
+    })();
+    BABYLON.Effect = Effect;
+})(BABYLON || (BABYLON = {}));

+ 37 - 38
src/Materials/babylon.fresnelParameters.js

@@ -1,38 +1,37 @@
-var BABYLON;
-(function (BABYLON) {
-    var FresnelParameters = (function () {
-        function FresnelParameters() {
-            this.isEnabled = true;
-            this.leftColor = BABYLON.Color3.White();
-            this.rightColor = BABYLON.Color3.Black();
-            this.bias = 0;
-            this.power = 1;
-        }
-        FresnelParameters.prototype.clone = function () {
-            var newFresnelParameters = new FresnelParameters();
-            BABYLON.Tools.DeepCopy(this, newFresnelParameters);
-            return new FresnelParameters;
-        };
-        FresnelParameters.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.isEnabled = this.isEnabled;
-            serializationObject.leftColor = this.leftColor;
-            serializationObject.rightColor = this.rightColor;
-            serializationObject.bias = this.bias;
-            serializationObject.power = this.power;
-            return serializationObject;
-        };
-        FresnelParameters.Parse = function (parsedFresnelParameters) {
-            var fresnelParameters = new FresnelParameters();
-            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
-            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
-            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
-            fresnelParameters.bias = parsedFresnelParameters.bias;
-            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
-            return fresnelParameters;
-        };
-        return FresnelParameters;
-    }());
-    BABYLON.FresnelParameters = FresnelParameters;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.fresnelParameters.js.map
+var BABYLON;
+(function (BABYLON) {
+    var FresnelParameters = (function () {
+        function FresnelParameters() {
+            this.isEnabled = true;
+            this.leftColor = BABYLON.Color3.White();
+            this.rightColor = BABYLON.Color3.Black();
+            this.bias = 0;
+            this.power = 1;
+        }
+        FresnelParameters.prototype.clone = function () {
+            var newFresnelParameters = new FresnelParameters();
+            BABYLON.Tools.DeepCopy(this, newFresnelParameters);
+            return new FresnelParameters;
+        };
+        FresnelParameters.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.isEnabled = this.isEnabled;
+            serializationObject.leftColor = this.leftColor;
+            serializationObject.rightColor = this.rightColor;
+            serializationObject.bias = this.bias;
+            serializationObject.power = this.power;
+            return serializationObject;
+        };
+        FresnelParameters.Parse = function (parsedFresnelParameters) {
+            var fresnelParameters = new FresnelParameters();
+            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
+            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
+            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
+            fresnelParameters.bias = parsedFresnelParameters.bias;
+            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
+            return fresnelParameters;
+        };
+        return FresnelParameters;
+    })();
+    BABYLON.FresnelParameters = FresnelParameters;
+})(BABYLON || (BABYLON = {}));

+ 0 - 0
src/Materials/babylon.material.js


Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels