Переглянути джерело

Port to Typescript step 3

David Catuhe 11 роки тому
батько
коміт
18d09ec94a
100 змінених файлів з 3854 додано та 1819 видалено
  1. 4 0
      Babylon/Animations/babylon.animation.js
  2. 4 0
      Babylon/Animations/babylon.animation.ts
  3. 80 67
      Babylon/Bones/babylon.bone.js
  4. 90 0
      Babylon/Bones/babylon.bone.ts
  5. 69 68
      Babylon/Bones/babylon.skeleton.js
  6. 84 0
      Babylon/Bones/babylon.skeleton.ts
  7. 0 1
      Babylon/Cameras/babylon.anaglyphCamera.js
  8. 1 2
      Babylon/Cameras/babylon.anaglyphCamera.ts
  9. 3 4
      Babylon/Cameras/babylon.arcRotateCamera.js
  10. 17 20
      Babylon/Cameras/babylon.arcRotateCamera.ts
  11. 2 5
      Babylon/Cameras/babylon.camera.js
  12. 5 8
      Babylon/Cameras/babylon.camera.ts
  13. 11 8
      Babylon/Cameras/babylon.freeCamera.js
  14. 21 18
      Babylon/Cameras/babylon.freeCamera.ts
  15. 42 33
      Babylon/Cameras/babylon.virtualJoysticksCamera.js
  16. 38 0
      Babylon/Cameras/babylon.virtualJoysticksCamera.ts
  17. 0 1
      Babylon/Collisions/babylon.collider.js
  18. 2 3
      Babylon/Collisions/babylon.collider.ts
  19. 11 0
      Babylon/Collisions/babylon.pickingInfo.js
  20. 7 0
      Babylon/Collisions/babylon.pickingInfo.ts
  21. 1 1
      Babylon/Culling/babylon.boundingBox.js
  22. 0 1
      Babylon/Culling/babylon.boundingInfo.js
  23. 1 2
      Babylon/Culling/babylon.boundingInfo.ts
  24. 94 100
      Babylon/Layer/babylon.layer.js
  25. 104 0
      Babylon/Layer/babylon.layer.ts
  26. 23 29
      Babylon/LensFlare/babylon.lensFlare.js
  27. 26 0
      Babylon/LensFlare/babylon.lensFlare.ts
  28. 181 193
      Babylon/LensFlare/babylon.lensFlareSystem.js
  29. 219 0
      Babylon/LensFlare/babylon.lensFlareSystem.ts
  30. 133 145
      Babylon/Lights/Shadows/babylon.shadowGenerator.js
  31. 161 0
      Babylon/Lights/Shadows/babylon.shadowGenerator.ts
  32. 0 4
      Babylon/Lights/babylon.directionalLight.js
  33. 3 7
      Babylon/Lights/babylon.directionalLight.ts
  34. 0 5
      Babylon/Lights/babylon.hemisphericLight.js
  35. 3 8
      Babylon/Lights/babylon.hemisphericLight.ts
  36. 3 6
      Babylon/Lights/babylon.light.js
  37. 7 12
      Babylon/Lights/babylon.light.ts
  38. 0 5
      Babylon/Lights/babylon.pointLight.js
  39. 3 9
      Babylon/Lights/babylon.pointLight.ts
  40. 0 4
      Babylon/Lights/babylon.spotLight.js
  41. 2 6
      Babylon/Lights/babylon.spotLight.ts
  42. 2 2
      Babylon/Materials/babylon.effect.ts
  43. 0 2
      Babylon/Materials/babylon.material.js
  44. 4 5
      Babylon/Materials/babylon.material.ts
  45. 0 1
      Babylon/Materials/babylon.multiMaterial.js
  46. 1 2
      Babylon/Materials/babylon.multiMaterial.ts
  47. 0 1
      Babylon/Materials/babylon.shaderMaterial.js
  48. 1 2
      Babylon/Materials/babylon.shaderMaterial.ts
  49. 12 19
      Babylon/Materials/babylon.standardMaterial.js
  50. 35 35
      Babylon/Materials/babylon.standardMaterial.ts
  51. 2 7
      Babylon/Materials/textures/babylon.baseTexture.js
  52. 9 13
      Babylon/Materials/textures/babylon.baseTexture.ts
  53. 3 4
      Babylon/Materials/textures/babylon.cubeTexture.js
  54. 4 5
      Babylon/Materials/textures/babylon.cubeTexture.ts
  55. 1 2
      Babylon/Materials/textures/babylon.mirrorTexture.js
  56. 2 3
      Babylon/Materials/textures/babylon.mirrorTexture.ts
  57. 19 11
      Babylon/Materials/textures/babylon.renderTargetTexture.js
  58. 22 14
      Babylon/Materials/textures/babylon.renderTargetTexture.ts
  59. 4 4
      Babylon/Materials/textures/babylon.texture.js
  60. 7 7
      Babylon/Materials/textures/babylon.texture.ts
  61. 1 5
      Babylon/Math/babylon.math.js
  62. 2 6
      Babylon/Math/babylon.math.ts
  63. 0 2
      Babylon/Mesh/babylon.csg.js
  64. 2 4
      Babylon/Mesh/babylon.csg.ts
  65. 18 74
      Babylon/Mesh/babylon.mesh.js
  66. 35 89
      Babylon/Mesh/babylon.mesh.ts
  67. 57 0
      Babylon/Mesh/babylon.mesh.vertexData.js
  68. 59 0
      Babylon/Mesh/babylon.mesh.vertexData.ts
  69. 0 3
      Babylon/Mesh/babylon.subMesh.js
  70. 5 8
      Babylon/Mesh/babylon.subMesh.ts
  71. 0 1
      Babylon/Mesh/babylon.vertexBuffer.js
  72. 3 4
      Babylon/Mesh/babylon.vertexBuffer.ts
  73. 19 18
      Babylon/Particles/babylon.particle.js
  74. 13 0
      Babylon/Particles/babylon.particle.ts
  75. 313 329
      Babylon/Particles/babylon.particleSystem.js
  76. 406 0
      Babylon/Particles/babylon.particleSystem.ts
  77. 0 1
      Babylon/PostProcess/babylon.anaglyphPostProcess.js
  78. 1 2
      Babylon/PostProcess/babylon.anaglyphPostProcess.ts
  79. 0 1
      Babylon/PostProcess/babylon.passPostProcess.js
  80. 1 2
      Babylon/PostProcess/babylon.passPostProcess.ts
  81. 8 6
      Babylon/PostProcess/babylon.postProcess.js
  82. 10 9
      Babylon/PostProcess/babylon.postProcess.ts
  83. 2 3
      Babylon/Rendering/babylon.renderingGroup.js
  84. 4 5
      Babylon/Rendering/babylon.renderingGroup.ts
  85. 0 1
      Babylon/Rendering/babylon.renderingManager.js
  86. 2 3
      Babylon/Rendering/babylon.renderingManager.ts
  87. 4 5
      Babylon/Sprites/babylon.spriteManager.js
  88. 11 12
      Babylon/Sprites/babylon.spriteManager.ts
  89. 55 50
      Babylon/Tools/babylon.sceneSerializer.js
  90. 559 0
      Babylon/Tools/babylon.sceneSerializer.ts
  91. 7 0
      Babylon/Tools/babylon.tags.js
  92. 7 0
      Babylon/Tools/babylon.tags.ts
  93. 1 1
      Babylon/Tools/babylon.tools.ts
  94. 169 172
      Babylon/Tools/babylon.virtualJoystick.js
  95. 360 0
      Babylon/Tools/babylon.virtualJoystick.ts
  96. 52 37
      Babylon/babylon.engine.js
  97. 69 50
      Babylon/babylon.engine.ts
  98. 16 0
      Babylon/babylon.mixins.ts
  99. 0 2
      Babylon/babylon.node.js
  100. 0 0
      Babylon/babylon.node.ts

+ 4 - 0
Babylon/Animations/babylon.animation.js

@@ -14,6 +14,10 @@
             this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
             this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
         }
         }
         // Methods
         // Methods
+        Animation.prototype.getKeys = function () {
+            return this._keys;
+        };
+
         Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
         Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
             return startValue + (endValue - startValue) * gradient;
             return startValue + (endValue - startValue) * gradient;
         };
         };

+ 4 - 0
Babylon/Animations/babylon.animation.ts

@@ -14,6 +14,10 @@
         }
         }
 
 
         // Methods   
         // Methods   
+        public getKeys(): any[] {
+            return this._keys;
+        }
+
         public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
         public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
             return startValue + (endValue - startValue) * gradient;
             return startValue + (endValue - startValue) * gradient;
         }
         }

+ 80 - 67
Babylon/Bones/babylon.bone.js

@@ -1,75 +1,88 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.Bone = function (name, skeleton, parentBone, matrix) {
-        this.name = name;
-        this._skeleton = skeleton;
-        this._matrix = matrix;
-        this._baseMatrix = matrix;
-        this._worldTransform = new BABYLON.Matrix();
-        this._absoluteTransform = new BABYLON.Matrix();
-        this._invertedAbsoluteTransform = new BABYLON.Matrix();
-        this.children = [];
-        this.animations = [];
-
-        skeleton.bones.push(this);
-        
-        if (parentBone) {
-            this._parent = parentBone;
-            parentBone.children.push(this);
-        } else {
-            this._parent = null;
-        }
-        
-        this._updateDifferenceMatrix();
-    };
-        
-    // Members
-    BABYLON.Bone.prototype.getParent = function() {
-        return this._parent;
-    };
-    
-    BABYLON.Bone.prototype.getLocalMatrix = function () {
-        return this._matrix;
-    };
-
-    BABYLON.Bone.prototype.getAbsoluteMatrix = function () {
-        var matrix = this._matrix.clone();
-        var parent = this._parent;
-
-        while (parent) {
-            matrix = matrix.multiply(parent.getLocalMatrix());
-            parent = parent.getParent();
+var BABYLON;
+(function (BABYLON) {
+    var Bone = (function () {
+        function Bone(name, skeleton, parentBone, matrix) {
+            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;
+
+            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;
+        };
 
 
-        return matrix;
-    };
+        Bone.prototype.getLocalMatrix = function () {
+            return this._matrix;
+        };
 
 
-    // Methods
-    BABYLON.Bone.prototype.updateMatrix = function(matrix) {
-        this._matrix = matrix;
-        this._skeleton._markAsDirty();
+        Bone.prototype.getBaseMatrix = function () {
+            return this._baseMatrix;
+        };
 
 
-        this._updateDifferenceMatrix();
-    };
+        Bone.prototype.getWorldMatrix = function () {
+            return this._worldTransform;
+        };
 
 
-    BABYLON.Bone.prototype._updateDifferenceMatrix = function() {
-        if (this._parent) {
-            this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
-        } else {
-            this._absoluteTransform.copyFrom(this._matrix);
-        }
+        Bone.prototype.getInvertedAbsoluteTransform = function () {
+            return this._invertedAbsoluteTransform;
+        };
 
 
-        this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
+        Bone.prototype.getAbsoluteMatrix = function () {
+            var matrix = this._matrix.clone();
+            var parent = this._parent;
 
 
-        for (var index = 0; index < this.children.length; index++) {
-            this.children[index]._updateDifferenceMatrix();
-        }
-    };
+            while (parent) {
+                matrix = matrix.multiply(parent.getLocalMatrix());
+                parent = parent.getParent();
+            }
+
+            return matrix;
+        };
+
+        // Methods
+        Bone.prototype.updateMatrix = function (matrix) {
+            this._matrix = matrix;
+            this._skeleton._markAsDirty();
+
+            this._updateDifferenceMatrix();
+        };
+
+        Bone.prototype._updateDifferenceMatrix = function () {
+            if (this._parent) {
+                this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
+            } else {
+                this._absoluteTransform.copyFrom(this._matrix);
+            }
+
+            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
+
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._updateDifferenceMatrix();
+            }
+        };
 
 
-    BABYLON.Bone.prototype.markAsDirty = function() {
-        this._skeleton._markAsDirty();
-    };
-})();
+        Bone.prototype.markAsDirty = function () {
+            this._skeleton._markAsDirty();
+        };
+        return Bone;
+    })();
+    BABYLON.Bone = Bone;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.bone.js.map

+ 90 - 0
Babylon/Bones/babylon.bone.ts

@@ -0,0 +1,90 @@
+module BABYLON {
+    export class Bone {
+        public children = new Array<Bone>();
+        public animations = new Array<Animation>();
+
+        private _skeleton: Skeleton;
+        private _matrix: Matrix;
+        private _baseMatrix: Matrix;
+        private _worldTransform = new BABYLON.Matrix();
+        private _absoluteTransform = new BABYLON.Matrix();
+        private _invertedAbsoluteTransform = new BABYLON.Matrix();
+        private _parent: Bone;
+
+        constructor(public name: string, skeleton: Skeleton, parentBone: Bone, matrix: Matrix) {
+            this._skeleton = skeleton;
+            this._matrix = matrix;
+            this._baseMatrix = matrix;
+
+            skeleton.bones.push(this);
+
+            if (parentBone) {
+                this._parent = parentBone;
+                parentBone.children.push(this);
+            } else {
+                this._parent = null;
+            }
+
+            this._updateDifferenceMatrix();
+        }
+
+        // Members
+        public getParent():Bone {
+            return this._parent;
+        }
+
+        public getLocalMatrix():Matrix {
+            return this._matrix;
+        }
+
+        public getBaseMatrix(): Matrix {
+            return this._baseMatrix;
+        }
+
+        public getWorldMatrix(): Matrix {
+            return this._worldTransform;
+        }
+
+        public getInvertedAbsoluteTransform(): Matrix {
+            return this._invertedAbsoluteTransform;
+        }
+
+        public getAbsoluteMatrix(): Matrix {
+            var matrix = this._matrix.clone();
+            var parent = this._parent;
+
+            while (parent) {
+                matrix = matrix.multiply(parent.getLocalMatrix());
+                parent = parent.getParent();
+            }
+
+            return matrix;
+        }
+
+        // Methods
+        public updateMatrix(matrix: Matrix): void {
+            this._matrix = matrix;
+            this._skeleton._markAsDirty();
+
+            this._updateDifferenceMatrix();
+        }
+
+        private _updateDifferenceMatrix(): void {
+            if (this._parent) {
+                this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
+            } else {
+                this._absoluteTransform.copyFrom(this._matrix);
+            }
+
+            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
+
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._updateDifferenceMatrix();
+            }
+        }
+
+        public markAsDirty(): void {
+            this._skeleton._markAsDirty();
+        }
+    }
+} 

+ 69 - 68
Babylon/Bones/babylon.skeleton.js

@@ -1,83 +1,84 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.Skeleton = function (name, id, scene) {
-        this.id = id;
-        this.name = name;
-        this.bones = [];
+var BABYLON;
+(function (BABYLON) {
+    var Skeleton = (function () {
+        function Skeleton(name, id, scene) {
+            this.name = name;
+            this.id = id;
+            this.bones = new Array();
+            this._isDirty = true;
+            this.bones = [];
+
+            this._scene = scene;
+
+            scene.skeletons.push(this);
+        }
+        // Members
+        Skeleton.prototype.getTransformMatrices = function () {
+            return this._transformMatrices;
+        };
+
+        // Methods
+        Skeleton.prototype._markAsDirty = function () {
+            this._isDirty = true;
+        };
+
+        Skeleton.prototype.prepare = function () {
+            if (!this._isDirty) {
+                return;
+            }
 
 
-        this._scene = scene;
+            if (!this._transformMatrices || this._transformMatrices.length !== 16 * this.bones.length) {
+                this._transformMatrices = new Float32Array(16 * this.bones.length);
+            }
 
 
-        scene.skeletons.push(this);
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var parentBone = bone.getParent();
 
 
-        this._isDirty = true;
-    };
-        
-    // Members
-    BABYLON.Skeleton.prototype.getTransformMatrices = function () {       
-        return this._transformMatrices;
-    };
+                if (parentBone) {
+                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
+                } else {
+                    bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
+                }
 
 
-    // Methods
-    BABYLON.Skeleton.prototype._markAsDirty = function() {
-        this._isDirty = true;
-    };
+                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
+            }
 
 
-    BABYLON.Skeleton.prototype.prepare = function() {
-        if (!this._isDirty) {
-            return;
-        }
+            this._isDirty = false;
+        };
 
 
-        if (!this._transformMatrices || this._transformMatrices.length !== 16 * this.bones.length) {
-            this._transformMatrices = new Float32Array(16 * this.bones.length);
-        }
+        Skeleton.prototype.getAnimatables = function () {
+            if (!this._animatables || this._animatables.length != this.bones.length) {
+                this._animatables = [];
 
 
-        for (var index = 0; index < this.bones.length; index++) {
-            var bone = this.bones[index];
-            var parentBone = bone.getParent();
-
-            if (parentBone) {
-                bone._matrix.multiplyToRef(parentBone._worldTransform, bone._worldTransform);
-            } else {
-                bone._worldTransform.copyFrom(bone._matrix);
+                for (var index = 0; index < this.bones.length; index++) {
+                    this._animatables.push(this.bones[index]);
+                }
             }
             }
 
 
-            bone._invertedAbsoluteTransform.multiplyToArray(bone._worldTransform, this._transformMatrices, index * 16);
-        }
+            return this._animatables;
+        };
 
 
-        this._isDirty = false;
-    };
-    
-    BABYLON.Skeleton.prototype.getAnimatables = function () {
-        if (!this._animatables || this._animatables.length != this.bones.length) {
-            this._animatables = [];
-            
-            for (var index = 0; index < this.bones.length; index++) {
-                this._animatables.push(this.bones[index]);
-            }
-        }
+        Skeleton.prototype.clone = function (name, id) {
+            var result = new BABYLON.Skeleton(name, id || name, this._scene);
 
 
-        return this._animatables;
-    };
+            for (var index = 0; index < this.bones.length; index++) {
+                var source = this.bones[index];
+                var parentBone = null;
 
 
-    BABYLON.Skeleton.prototype.clone = function(name, id) {
-        var result = new BABYLON.Skeleton(name, id || name, this._scene);
+                if (source.getParent()) {
+                    var parentIndex = this.bones.indexOf(source.getParent());
+                    parentBone = result.bones[parentIndex];
+                }
 
 
-        for (var index = 0; index < this.bones.length; index++) {
-            var source = this.bones[index];
-            var parentBone = null;
-            
-            if (source.getParent()) {
-                var parentIndex = this.bones.indexOf(source.getParent());
-                parentBone = result.bones[parentIndex];
+                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
+                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
             }
             }
 
 
-            var bone = new BABYLON.Bone(source.name, result, parentBone, source._baseMatrix);
-            BABYLON.Tools.DeepCopy(source.animations, bone.animations);
-        }
-
-        return result;
-    };
-})();
+            return result;
+        };
+        return Skeleton;
+    })();
+    BABYLON.Skeleton = Skeleton;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.skeleton.js.map

+ 84 - 0
Babylon/Bones/babylon.skeleton.ts

@@ -0,0 +1,84 @@
+module BABYLON {
+    export class Skeleton {
+        public bones = new Array<Bone>();
+
+        private _scene: Scene;
+        private _isDirty = true;
+        private _transformMatrices: Float32Array;
+        private _animatables: IAnimatable[];
+
+        constructor(public name: string, public id: string, scene: Scene) {
+            this.bones = [];
+
+            this._scene = scene;
+
+            scene.skeletons.push(this);
+        }
+
+        // Members
+        public getTransformMatrices() {
+            return this._transformMatrices;
+        }
+
+        // Methods
+        public _markAsDirty(): void {
+            this._isDirty = true;
+        }
+
+        public prepare(): void {
+            if (!this._isDirty) {
+                return;
+            }
+
+            if (!this._transformMatrices || this._transformMatrices.length !== 16 * this.bones.length) {
+                this._transformMatrices = new Float32Array(16 * this.bones.length);
+            }
+
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var parentBone = bone.getParent();
+
+                if (parentBone) {
+                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
+                } else {
+                    bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
+                }
+
+                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
+            }
+
+            this._isDirty = false;
+        }
+
+        public getAnimatables(): IAnimatable[] {
+            if (!this._animatables || this._animatables.length != this.bones.length) {
+                this._animatables = [];
+
+                for (var index = 0; index < this.bones.length; index++) {
+                    this._animatables.push(this.bones[index]);
+                }
+            }
+
+            return this._animatables;
+        }
+
+        public clone(name: string, id: string): Skeleton {
+            var result = new BABYLON.Skeleton(name, id || name, this._scene);
+
+            for (var index = 0; index < this.bones.length; index++) {
+                var source = this.bones[index];
+                var parentBone = null;
+
+                if (source.getParent()) {
+                    var parentIndex = this.bones.indexOf(source.getParent());
+                    parentBone = result.bones[parentIndex];
+                }
+
+                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
+                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
+            }
+
+            return result;
+        }
+    }
+}

+ 0 - 1
Babylon/Cameras/babylon.anaglyphCamera.js

@@ -62,7 +62,6 @@ var BABYLON;
 
 
     var AnaglyphFreeCamera = (function (_super) {
     var AnaglyphFreeCamera = (function (_super) {
         __extends(AnaglyphFreeCamera, _super);
         __extends(AnaglyphFreeCamera, _super);
-        //ANY
         function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
         function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
             _super.call(this, name, position, scene);
             _super.call(this, name, position, scene);
 
 

+ 1 - 2
Babylon/Cameras/babylon.anaglyphCamera.ts

@@ -61,8 +61,7 @@
         private _rightCamera: FreeCamera;
         private _rightCamera: FreeCamera;
         private _transformMatrix: Matrix;
         private _transformMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, position: Vector3, eyeSpace: number, scene) {
+        constructor(name: string, position: Vector3, eyeSpace: number, scene: Scene) {
             super(name, position, scene);
             super(name, position, scene);
 
 
             this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
             this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);

+ 3 - 4
Babylon/Cameras/babylon.arcRotateCamera.js

@@ -10,7 +10,6 @@ var BABYLON;
 
 
     var ArcRotateCamera = (function (_super) {
     var ArcRotateCamera = (function (_super) {
         __extends(ArcRotateCamera, _super);
         __extends(ArcRotateCamera, _super);
-        //ANY
         function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
         function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
             _super.call(this, name, BABYLON.Vector3.Zero(), scene);
             _super.call(this, name, BABYLON.Vector3.Zero(), scene);
             this.alpha = alpha;
             this.alpha = alpha;
@@ -303,13 +302,13 @@ var BABYLON;
                 this.inertialBetaOffset *= this.inertia;
                 this.inertialBetaOffset *= this.inertia;
                 this.inertialRadiusOffset *= this.inertia;
                 this.inertialRadiusOffset *= this.inertia;
 
 
-                if (Math.abs(this.inertialAlphaOffset) < 0.001)
+                if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
                     this.inertialAlphaOffset = 0;
                     this.inertialAlphaOffset = 0;
 
 
-                if (Math.abs(this.inertialBetaOffset) < 0.001)
+                if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
                     this.inertialBetaOffset = 0;
                     this.inertialBetaOffset = 0;
 
 
-                if (Math.abs(this.inertialRadiusOffset) < 0.001)
+                if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
                     this.inertialRadiusOffset = 0;
                     this.inertialRadiusOffset = 0;
             }
             }
 
 

+ 17 - 20
Babylon/Cameras/babylon.arcRotateCamera.ts

@@ -1,6 +1,4 @@
 module BABYLON {
 module BABYLON {
-    declare var window;
-
     var eventPrefix = Tools.GetPointerPrefix();
     var eventPrefix = Tools.GetPointerPrefix();
 
 
     export class ArcRotateCamera extends Camera {
     export class ArcRotateCamera extends Camera {
@@ -25,21 +23,20 @@
         private _viewMatrix = new BABYLON.Matrix();
         private _viewMatrix = new BABYLON.Matrix();
         private _attachedElement: HTMLElement;
         private _attachedElement: HTMLElement;
 
 
-        private _onPointerDown; //ANY
-        private _onPointerUp; //ANY
-        private _onPointerMove; //ANY
-        private _wheel; //ANY
-        private _onMouseMove; //ANY
-        private _onKeyDown; //ANY
-        private _onKeyUp; //ANY
-        private _onLostFocus; //ANY
-        private _reset; //ANY
-        private _onGestureStart; //ANY
-        private _onGesture; //ANY
-        private _MSGestureHandler;
-
-        //ANY
-        constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene) {
+        private _onPointerDown: (e: PointerEvent) => void;
+        private _onPointerUp: (e: PointerEvent) => void;
+        private _onPointerMove: (e: PointerEvent) => void;
+        private _wheel: (e: MouseWheelEvent) => void;
+        private _onMouseMove: (e: MouseEvent) => any;
+        private _onKeyDown: (e: KeyboardEvent) => any;
+        private _onKeyUp: (e: KeyboardEvent) => any;
+        private _onLostFocus: (e: FocusEvent) => any;
+        private _reset: () => void;
+        private _onGestureStart: (e: PointerEvent) => void;
+        private _onGesture: (e: MSGestureEvent) => void;
+        private _MSGestureHandler: MSGesture;
+
+        constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
             super(name, BABYLON.Vector3.Zero(), scene);
             super(name, BABYLON.Vector3.Zero(), scene);
 
 
             this.getViewMatrix();
             this.getViewMatrix();
@@ -323,13 +320,13 @@
                 this.inertialBetaOffset *= this.inertia;
                 this.inertialBetaOffset *= this.inertia;
                 this.inertialRadiusOffset *= this.inertia;
                 this.inertialRadiusOffset *= this.inertia;
 
 
-                if (Math.abs(this.inertialAlphaOffset) < 0.001) //ANY BABYLON.Engine.epsilon
+                if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
                     this.inertialAlphaOffset = 0;
                     this.inertialAlphaOffset = 0;
 
 
-                if (Math.abs(this.inertialBetaOffset) < 0.001) //ANY BABYLON.Engine.epsilon
+                if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
                     this.inertialBetaOffset = 0;
                     this.inertialBetaOffset = 0;
 
 
-                if (Math.abs(this.inertialRadiusOffset) < 0.001) //ANY BABYLON.Engine.epsilon
+                if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
                     this.inertialRadiusOffset = 0;
                     this.inertialRadiusOffset = 0;
             }
             }
 
 

+ 2 - 5
Babylon/Cameras/babylon.camera.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var Camera = (function (_super) {
     var Camera = (function (_super) {
         __extends(Camera, _super);
         __extends(Camera, _super);
-        //ANY
         function Camera(name, position, scene) {
         function Camera(name, position, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this.position = position;
             this.position = position;
@@ -129,10 +128,9 @@ var BABYLON;
         Camera.prototype._update = function () {
         Camera.prototype._update = function () {
         };
         };
 
 
-        //ANY
         Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
         Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
             if (typeof insertAt === "undefined") { insertAt = null; }
             if (typeof insertAt === "undefined") { insertAt = null; }
-            if (!postProcess._reusable && this._postProcesses.indexOf(postProcess) > -1) {
+            if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
                 console.error("You're trying to reuse a post process not defined as reusable.");
                 console.error("You're trying to reuse a post process not defined as reusable.");
                 return 0;
                 return 0;
             }
             }
@@ -156,7 +154,7 @@ var BABYLON;
                 add = 1;
                 add = 1;
             }
             }
 
 
-            for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
+            for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
                 if (this._postProcessesTakenIndices[i] < insertAt) {
                 if (this._postProcessesTakenIndices[i] < insertAt) {
                     continue;
                     continue;
                 }
                 }
@@ -180,7 +178,6 @@ var BABYLON;
             return result;
             return result;
         };
         };
 
 
-        //ANY
         Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
         Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
             if (typeof atIndices === "undefined") { atIndices = null; }
             if (typeof atIndices === "undefined") { atIndices = null; }
             var result = [];
             var result = [];

+ 5 - 8
Babylon/Cameras/babylon.camera.ts

@@ -25,8 +25,7 @@
         public _postProcesses = [];
         public _postProcesses = [];
         public _postProcessesTakenIndices = [];
         public _postProcessesTakenIndices = [];
 
 
-        //ANY
-        constructor(name: string, public position: Vector3, scene) {
+        constructor(name: string, public position: Vector3, scene: Scene) {
             super(name, scene);
             super(name, scene);
 
 
             scene.cameras.push(this);
             scene.cameras.push(this);
@@ -139,9 +138,8 @@
         public _update(): void {
         public _update(): void {
         }
         }
 
 
-        //ANY
-        public attachPostProcess(postProcess, insertAt: number = null): number {
-            if (!postProcess._reusable && this._postProcesses.indexOf(postProcess) > -1) {
+        public attachPostProcess(postProcess: PostProcess, insertAt: number = null): number {
+            if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
                 console.error("You're trying to reuse a post process not defined as reusable.");
                 console.error("You're trying to reuse a post process not defined as reusable.");
                 return 0;
                 return 0;
             }
             }
@@ -167,7 +165,7 @@
                 add = 1;
                 add = 1;
             }
             }
 
 
-            for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
+            for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
                 if (this._postProcessesTakenIndices[i] < insertAt) {
                 if (this._postProcessesTakenIndices[i] < insertAt) {
                     continue;
                     continue;
                 }
                 }
@@ -191,8 +189,7 @@
             return result;
             return result;
         }
         }
 
 
-        //ANY
-        public detachPostProcess(postProcess, atIndices: any = null): number[] {
+        public detachPostProcess(postProcess: PostProcess, atIndices: any = null): number[] {
             var result = [];
             var result = [];
 
 
             if (!atIndices) {
             if (!atIndices) {

+ 11 - 8
Babylon/Cameras/babylon.freeCamera.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var FreeCamera = (function (_super) {
     var FreeCamera = (function (_super) {
         __extends(FreeCamera, _super);
         __extends(FreeCamera, _super);
-        //ANY
         function FreeCamera(name, position, scene) {
         function FreeCamera(name, position, scene) {
             _super.call(this, name, position, scene);
             _super.call(this, name, position, scene);
             this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
             this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
@@ -267,7 +266,7 @@ var BABYLON;
             this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
             this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
             this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
             this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
 
 
-            if (this._diffPosition.length() > 0.001) {
+            if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
                 this.position.addInPlace(this._diffPosition);
                 this.position.addInPlace(this._diffPosition);
                 if (this.onCollide) {
                 if (this.onCollide) {
                     this.onCollide(this._collider.collidedMesh);
                     this.onCollide(this._collider.collidedMesh);
@@ -339,24 +338,28 @@ var BABYLON;
 
 
             // Inertia
             // Inertia
             if (needToMove) {
             if (needToMove) {
-                if (Math.abs(this.cameraDirection.x) < 0.001)
+                if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.x = 0;
                     this.cameraDirection.x = 0;
+                }
 
 
-                if (Math.abs(this.cameraDirection.y) < 0.001)
+                if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.y = 0;
                     this.cameraDirection.y = 0;
+                }
 
 
-                if (Math.abs(this.cameraDirection.z) < 0.001)
+                if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.z = 0;
                     this.cameraDirection.z = 0;
+                }
 
 
                 this.cameraDirection.scaleInPlace(this.inertia);
                 this.cameraDirection.scaleInPlace(this.inertia);
             }
             }
             if (needToRotate) {
             if (needToRotate) {
-                if (Math.abs(this.cameraRotation.x) < 0.001)
+                if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
                     this.cameraRotation.x = 0;
                     this.cameraRotation.x = 0;
+                }
 
 
-                if (Math.abs(this.cameraRotation.y) < 0.001)
+                if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
                     this.cameraRotation.y = 0;
                     this.cameraRotation.y = 0;
-
+                }
                 this.cameraRotation.scaleInPlace(this.inertia);
                 this.cameraRotation.scaleInPlace(this.inertia);
             }
             }
         };
         };

+ 21 - 18
Babylon/Cameras/babylon.freeCamera.ts

@@ -35,17 +35,16 @@
         private _localDirection: Vector3;
         private _localDirection: Vector3;
         private _transformedDirection: Vector3;
         private _transformedDirection: Vector3;
 
 
-        private _onMouseDown; //ANY
-        private _onMouseUp; //ANY
-        private _onMouseOut; //ANY
-        private _onMouseMove; //ANY
-        private _onKeyDown; //ANY
-        private _onKeyUp; //ANY
-        private _onLostFocus; //ANY
-        private _reset; //ANY
-
-        //ANY
-        constructor(name: string, position: Vector3, scene) {
+        private _onMouseDown: (e: MouseEvent) => any;
+        private _onMouseUp: (e: MouseEvent) => any;
+        private _onMouseOut: (e: MouseEvent) => any;
+        private _onMouseMove: (e: MouseEvent) => any;
+        private _onKeyDown: (e: KeyboardEvent) => any;
+        private _onKeyUp: (e: KeyboardEvent) => any;
+        private _onLostFocus: (e: FocusEvent) => any;
+        private _reset: () => void;
+
+        constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);
             super(name, position, scene);
         }
         }
 
 
@@ -282,7 +281,7 @@
             this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
             this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
             this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
             this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
 
 
-            if (this._diffPosition.length() > 0.001) {//ANY Engine.collisionEpsilon
+            if (this._diffPosition.length() > Engine.CollisionsEpsilon) {
                 this.position.addInPlace(this._diffPosition);
                 this.position.addInPlace(this._diffPosition);
                 if (this.onCollide) {
                 if (this.onCollide) {
                     this.onCollide(this._collider.collidedMesh);
                     this.onCollide(this._collider.collidedMesh);
@@ -358,24 +357,28 @@
 
 
             // Inertia
             // Inertia
             if (needToMove) {
             if (needToMove) {
-                if (Math.abs(this.cameraDirection.x) < 0.001) //ANY: BABYLON.Engine.epsilon
+                if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.x = 0;
                     this.cameraDirection.x = 0;
+                }
 
 
-                if (Math.abs(this.cameraDirection.y) < 0.001)
+                if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.y = 0;
                     this.cameraDirection.y = 0;
+                }
 
 
-                if (Math.abs(this.cameraDirection.z) < 0.001)
+                if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
                     this.cameraDirection.z = 0;
                     this.cameraDirection.z = 0;
+                }
 
 
                 this.cameraDirection.scaleInPlace(this.inertia);
                 this.cameraDirection.scaleInPlace(this.inertia);
             }
             }
             if (needToRotate) {
             if (needToRotate) {
-                if (Math.abs(this.cameraRotation.x) < 0.001)
+                if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
                     this.cameraRotation.x = 0;
                     this.cameraRotation.x = 0;
+                }
 
 
-                if (Math.abs(this.cameraRotation.y) < 0.001)
+                if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
                     this.cameraRotation.y = 0;
                     this.cameraRotation.y = 0;
-
+                }
                 this.cameraRotation.scaleInPlace(this.inertia);
                 this.cameraRotation.scaleInPlace(this.inertia);
             }
             }
         }
         }

+ 42 - 33
Babylon/Cameras/babylon.virtualJoysticksCamera.js

@@ -1,36 +1,45 @@
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.VirtualJoysticksCamera = function (name, position, scene) {
-        BABYLON.FreeCamera.call(this, name, position, scene);
-        this.leftjoystick = new BABYLON.VirtualJoystick(true);
-        this.leftjoystick.setAxisForUD("Z");
-        this.leftjoystick.setAxisForLR("X");
-        this.leftjoystick.setJoystickSensibility(0.15);
-        this.rightjoystick = new BABYLON.VirtualJoystick(false);
-        this.rightjoystick.setAxisForUD("X");
-        this.rightjoystick.setAxisForLR("Y");
-        this.rightjoystick.reverseUpDown = true;
-        this.rightjoystick.setJoystickSensibility(0.05);
-        this.rightjoystick.setJoystickColor("yellow");
-    };
-
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
     // We're mainly based on the logic defined into the FreeCamera code
     // We're mainly based on the logic defined into the FreeCamera code
-    BABYLON.VirtualJoysticksCamera.prototype = Object.create(BABYLON.FreeCamera.prototype);
-    BABYLON.VirtualJoysticksCamera.prototype._checkInputs = function () {
-        var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-        var deltaTransform = BABYLON.Vector3.TransformCoordinates(this.leftjoystick.deltaPosition, cameraTransform);
-        this.cameraDirection = this.cameraDirection.add(deltaTransform);
-        this.cameraRotation = this.cameraRotation.add(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);
+    var VirtualJoysticksCamera = (function (_super) {
+        __extends(VirtualJoysticksCamera, _super);
+        function VirtualJoysticksCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.leftjoystick = new BABYLON.VirtualJoystick(true);
+            this.leftjoystick.setAxisForUD(2 /* Z */);
+            this.leftjoystick.setAxisForLR(0 /* X */);
+            this.leftjoystick.setJoystickSensibility(0.15);
+            this.rightjoystick = new BABYLON.VirtualJoystick(false);
+            this.rightjoystick.setAxisForUD(0 /* X */);
+            this.rightjoystick.setAxisForLR(1 /* Y */);
+            this.rightjoystick.reverseUpDown = true;
+            this.rightjoystick.setJoystickSensibility(0.05);
+            this.rightjoystick.setJoystickColor("yellow");
         }
         }
-    };
+        VirtualJoysticksCamera.prototype._checkInputs = function () {
+            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+            var deltaTransform = BABYLON.Vector3.TransformCoordinates(this.leftjoystick.deltaPosition, cameraTransform);
+            this.cameraDirection = this.cameraDirection.add(deltaTransform);
+            this.cameraRotation = this.cameraRotation.add(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);
+            }
+        };
 
 
-    BABYLON.VirtualJoysticksCamera.prototype.dispose = function () {
-        this.leftjoystick.releaseCanvas();
-    };
-})();
+        VirtualJoysticksCamera.prototype.dispose = function () {
+            this.leftjoystick.releaseCanvas();
+        };
+        return VirtualJoysticksCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map

+ 38 - 0
Babylon/Cameras/babylon.virtualJoysticksCamera.ts

@@ -0,0 +1,38 @@
+module BABYLON {
+    // We're mainly based on the logic defined into the FreeCamera code
+    export class VirtualJoysticksCamera extends FreeCamera {
+        private leftjoystick: BABYLON.VirtualJoystick;
+        private rightjoystick: BABYLON.VirtualJoystick;
+
+        constructor(name, position, scene) {
+            super(name, position, scene);
+            this.leftjoystick = new BABYLON.VirtualJoystick(true);
+            this.leftjoystick.setAxisForUD(BABYLON.JoystickAxis.Z);
+            this.leftjoystick.setAxisForLR(BABYLON.JoystickAxis.X);
+            this.leftjoystick.setJoystickSensibility(0.15);
+            this.rightjoystick = new BABYLON.VirtualJoystick(false);
+            this.rightjoystick.setAxisForUD(BABYLON.JoystickAxis.X);
+            this.rightjoystick.setAxisForLR(BABYLON.JoystickAxis.Y);
+            this.rightjoystick.reverseUpDown = true;
+            this.rightjoystick.setJoystickSensibility(0.05);
+            this.rightjoystick.setJoystickColor("yellow");
+        }
+
+        public _checkInputs() {
+            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+            var deltaTransform = BABYLON.Vector3.TransformCoordinates(this.leftjoystick.deltaPosition, cameraTransform);
+            this.cameraDirection = this.cameraDirection.add(deltaTransform);
+            this.cameraRotation = this.cameraRotation.add(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);
+            }
+        }
+
+        public dispose() {
+            this.leftjoystick.releaseCanvas();
+        }
+    }
+}

+ 0 - 1
Babylon/Collisions/babylon.collider.js

@@ -124,7 +124,6 @@
             return true;
             return true;
         };
         };
 
 
-        //ANY
         Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
         Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
             var t0;
             var t0;
             var embeddedInPlane = false;
             var embeddedInPlane = false;

+ 2 - 3
Babylon/Collisions/babylon.collider.ts

@@ -68,7 +68,7 @@
         public initialPosition: Vector3;
         public initialPosition: Vector3;
         public nearestDistance: number;
         public nearestDistance: number;
         public intersectionPoint: Vector3;
         public intersectionPoint: Vector3;
-        public collidedMesh; //ANY
+        public collidedMesh: Mesh
 
 
         private _collisionPoint = BABYLON.Vector3.Zero();
         private _collisionPoint = BABYLON.Vector3.Zero();
         private _planeIntersectionPoint = BABYLON.Vector3.Zero();
         private _planeIntersectionPoint = BABYLON.Vector3.Zero();
@@ -133,8 +133,7 @@
             return true;
             return true;
         }
         }
 
 
-        //ANY
-        public _testTriangle(faceIndex: number, subMesh, p1: Vector3, p2: Vector3, p3: Vector3): void {
+        public _testTriangle(faceIndex: number, subMesh: SubMesh, p1: Vector3, p2: Vector3, p3: Vector3): void {
             var t0;
             var t0;
             var embeddedInPlane = false;
             var embeddedInPlane = false;
 
 

+ 11 - 0
Babylon/Collisions/babylon.pickingInfo.js

@@ -1,5 +1,16 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
+    var IntersectionInfo = (function () {
+        function IntersectionInfo(bu, bv, distance) {
+            this.bu = bu;
+            this.bv = bv;
+            this.distance = distance;
+            this.faceId = 0;
+        }
+        return IntersectionInfo;
+    })();
+    BABYLON.IntersectionInfo = IntersectionInfo;
+
     var PickingInfo = (function () {
     var PickingInfo = (function () {
         function PickingInfo() {
         function PickingInfo() {
             this.hit = false;
             this.hit = false;

+ 7 - 0
Babylon/Collisions/babylon.pickingInfo.ts

@@ -1,4 +1,11 @@
 module BABYLON {
 module BABYLON {
+    export class IntersectionInfo {
+        public faceId = 0;
+
+        constructor(public bu: number, public bv: number, public distance: number) {
+        }
+    }
+
     export class PickingInfo {
     export class PickingInfo {
         public hit = false;
         public hit = false;
         public distance = 0;
         public distance = 0;

+ 1 - 1
Babylon/Culling/babylon.boundingBox.js

@@ -144,4 +144,4 @@
     })();
     })();
     BABYLON.BoundingBox = BoundingBox;
     BABYLON.BoundingBox = BoundingBox;
 })(BABYLON || (BABYLON = {}));
 })(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.BoundingBox.js.map
+//# sourceMappingURL=babylon.boundingBox.js.map

+ 0 - 1
Babylon/Culling/babylon.boundingInfo.js

@@ -43,7 +43,6 @@
             return this.boundingBox.isInFrustum(frustumPlanes);
             return this.boundingBox.isInFrustum(frustumPlanes);
         };
         };
 
 
-        //ANY
         BoundingInfo.prototype._checkCollision = function (collider) {
         BoundingInfo.prototype._checkCollision = function (collider) {
             return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
             return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
         };
         };

+ 1 - 2
Babylon/Culling/babylon.boundingInfo.ts

@@ -44,8 +44,7 @@
             return this.boundingBox.isInFrustum(frustumPlanes);
             return this.boundingBox.isInFrustum(frustumPlanes);
         }
         }
 
 
-        //ANY
-        public _checkCollision(collider): boolean {
+        public _checkCollision(collider: Collider): boolean {
             return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
             return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
         }
         }
 
 

+ 94 - 100
Babylon/Layer/babylon.layer.js

@@ -1,101 +1,95 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.Layer = function (name, imgUrl, scene, isBackground, color) {
-        this.name = name;
-        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);
-        
-        // VBO
-        var vertices = [];
-        vertices.push(1, 1);
-        vertices.push(-1, 1);
-        vertices.push(-1, -1);
-        vertices.push(1, -1);
-        this._vertexDeclaration = [2];
-        this._vertexStrideSize = 2 * 4;
-        this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-
-        // Indices
-        var indices = [];
-        indices.push(0);
-        indices.push(1);
-        indices.push(2);
-
-        indices.push(0);
-        indices.push(2);
-        indices.push(3);
-
-        this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-        
-        // Effects
-        this._effect = this._scene.getEngine().createEffect("layer",
-                    ["position"],
-                    ["textureMatrix", "color"],
-                    ["textureSampler"], "");
-    };
-
-    // Members
-    BABYLON.Layer.prototype.onDispose = null;
-
-    // Methods
-    BABYLON.Layer.prototype.render = function () {
-        // Check
-        if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
-            return;
-
-        var engine = this._scene.getEngine();
-       
-        // Render
-        engine.enableEffect(this._effect);
-        engine.setState(false);
-
-        // Texture
-        this._effect.setTexture("textureSampler", this.texture);
-        this._effect.setMatrix("textureMatrix", this.texture._computeTextureMatrix());
-
-        // Color
-        this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
-
-        // VBOs
-        engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
-
-        // Draw order
-        engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-        engine.draw(true, 0, 6);
-        engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-    };
-    
-    BABYLON.Layer.prototype.dispose = function () {
-        if (this._vertexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-            this._vertexBuffer = null;
+var BABYLON;
+(function (BABYLON) {
+    var Layer = (function () {
+        function Layer(name, imgUrl, scene, isBackground, color) {
+            this.name = name;
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            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);
+
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
         }
         }
-
-        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
-        if (this.onDispose) {
-            this.onDispose();
-        }
-    };
-    
-})();
+        Layer.prototype.render = function () {
+            // Check
+            if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
+                return;
+
+            var engine = this._scene.getEngine();
+
+            // Render
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+
+            // Texture
+            this._effect.setTexture("textureSampler", this.texture);
+            this._effect.setMatrix("textureMatrix", this.texture._computeTextureMatrix());
+
+            // Color
+            this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+
+            // Draw order
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+            engine.draw(true, 0, 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+        };
+
+        Layer.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = 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
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        return Layer;
+    })();
+    BABYLON.Layer = Layer;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.layer.js.map

+ 104 - 0
Babylon/Layer/babylon.layer.ts

@@ -0,0 +1,104 @@
+module BABYLON {
+    export class Layer {
+        public texture: Texture;
+        public isBackground: boolean;
+        public color: Color4;
+        public onDispose: () => void;
+
+        private _scene: Scene;
+        private _vertexDeclaration = [2];
+        private _vertexStrideSize = 2 * 4;
+        private _vertexBuffer: WebGLBuffer;
+        private _indexBuffer: WebGLBuffer;
+        private _effect: Effect;
+
+        constructor(public name: string, imgUrl: string, scene: Scene, isBackground?: boolean, color?: Color4) {
+            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);
+
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("layer",
+                ["position"],
+                ["textureMatrix", "color"],
+                ["textureSampler"], "");
+        }
+
+        public render(): void {
+            // Check
+            if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
+                return;
+
+            var engine = this._scene.getEngine();
+
+            // Render
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+
+            // Texture
+            this._effect.setTexture("textureSampler", this.texture);
+            this._effect.setMatrix("textureMatrix", this.texture._computeTextureMatrix());
+
+            // Color
+            this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+
+            // Draw order
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+            engine.draw(true, 0, 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+        }
+
+        public dispose(): void {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = 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
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+    }
+} 

+ 23 - 29
Babylon/LensFlare/babylon.lensFlare.js

@@ -1,32 +1,26 @@
-"use strict";
+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();
+                }
 
 
-var BABYLON = BABYLON || {};
+                // 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;
 
 
-(function () {
-    BABYLON.LensFlare = function (size, position, color, imgUrl, system) {
-        this.color = color || new BABYLON.Color3(1, 1, 1);
-        this.position = position;
-        this.size = size;
-        this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
-        this._system = system;
-        
-        system.lensFlares.push(this);
-    };
-    
-    // Properties
-    BABYLON.LensFlare.prototype.position = 0;
-    BABYLON.LensFlare.prototype.size = 1.0;
-    BABYLON.LensFlare.prototype.texture = null;
-    
-    // Methods
-    BABYLON.LensFlare.prototype.dispose = function() {
-        if (this.texture) {
-            this.texture.dispose();
+            system.lensFlares.push(this);
         }
         }
-        
-        // Remove from scene
-        var index = this._system.lensFlares.indexOf(this);
-        this._system.lensFlares.splice(index, 1);
-    };
-    
-})();
+        return LensFlare;
+    })();
+    BABYLON.LensFlare = LensFlare;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.lensFlare.js.map

+ 26 - 0
Babylon/LensFlare/babylon.lensFlare.ts

@@ -0,0 +1,26 @@
+module BABYLON {
+    export class LensFlare {
+        public color: Color3;
+        public texture: Texture;
+
+        private _system: LensFlareSystem;
+
+        constructor(public size: number, public position: number, color, imgUrl: string, system: LensFlareSystem) {
+            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);
+        }
+
+        public dispose = function (): void {
+            if (this.texture) {
+                this.texture.dispose();
+            }
+
+            // Remove from scene
+            var index = this._system.lensFlares.indexOf(this);
+            this._system.lensFlares.splice(index, 1);
+        };
+    }
+} 

+ 181 - 193
Babylon/LensFlare/babylon.lensFlareSystem.js

@@ -1,214 +1,202 @@
-"use strict";
+var BABYLON;
+(function (BABYLON) {
+    var LensFlareSystem = (function () {
+        function LensFlareSystem(name, emitter, scene) {
+            this.name = name;
+            this.lensFlares = new Array();
+            this.borderLimit = 300;
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            this._scene = scene;
+            this._emitter = emitter;
+            scene.lensFlareSystems.push(this);
+
+            this.meshesSelectionPredicate = function (m) {
+                return m.material && m.isVisible && m.isEnabled() && m.checkCollisions;
+            };
+
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
+        }
+        LensFlareSystem.prototype.getScene = function () {
+            return this._scene;
+        };
+
+        LensFlareSystem.prototype.getEmitterPosition = function () {
+            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
+        };
 
 
-var BABYLON = BABYLON || {};
+        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
+            var position = this.getEmitterPosition();
 
 
-(function () {
-    BABYLON.LensFlareSystem = function (name, emitter, scene) {
-        this.lensFlares = [];
-        this._scene = scene;
-        this._emitter = emitter;
-        this.name = name;
+            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
 
 
-        scene.lensFlareSystems.push(this);
+            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;
+                }
+            }
 
 
-        this.meshesSelectionPredicate = function(m) {
-            return m.material && m.isVisible && m.isEnabled() && m.checkCollisions;
+            return false;
+        };
+
+        LensFlareSystem.prototype._isVisible = function () {
+            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;
         };
         };
-        
-        // VBO
-        var vertices = [];
-        vertices.push(1, 1);
-        vertices.push(-1, 1);
-        vertices.push(-1, -1);
-        vertices.push(1, -1);
-        this._vertexDeclaration = [2];
-        this._vertexStrideSize = 2 * 4;
-        this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-
-        // Indices
-        var indices = [];
-        indices.push(0);
-        indices.push(1);
-        indices.push(2);
-
-        indices.push(0);
-        indices.push(2);
-        indices.push(3);
-
-        this._indexBuffer = scene.getEngine().createIndexBuffer(indices);       
-
-        // Effects
-        this._effect = this._scene.getEngine().createEffect("lensFlare",
-                    ["position"],
-                    ["color", "viewportMatrix"],
-                    ["textureSampler"], "");
-    };
-
-    // Members
-    BABYLON.LensFlareSystem.prototype.borderLimit = 300;
-    
-    // Properties
-    BABYLON.LensFlareSystem.prototype.getScene = function() {
-        return this._scene;
-    };
-    
-    BABYLON.LensFlareSystem.prototype.getEmitterPosition = function() {
-        return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
-    };
-
-    // Methods
-    BABYLON.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;
+
+        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);
+
+            // Position
+            if (!this.computeEffectivePosition(globalViewport)) {
+                return false;
             }
             }
-        }
 
 
-        return false;
-    };
+            // Visibility
+            if (!this._isVisible()) {
+                return false;
+            }
 
 
-    BABYLON.LensFlareSystem.prototype._isVisible = function () {
-        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);
+            // Intensity
+            var awayX;
+            var awayY;
 
 
-        return !pickInfo.hit || pickInfo.distance > distance;
-    };
+            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;
+            }
 
 
-    BABYLON.LensFlareSystem.prototype.render = function () {
-        if (!this._effect.isReady())
-            return false;
+            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 engine = this._scene.getEngine();
-        var viewport = this._scene.activeCamera.viewport;
-        var globalViewport = viewport.toGlobal(engine);
-        
-        // Position
-        if (!this.computeEffectivePosition(globalViewport)) {
-            return false;
-        }
-        
-        // Visibility
-        if (!this._isVisible()) {
-            return false;
-        }
+            var away = (awayX > awayY) ? awayX : awayY;
+            if (away > this.borderLimit) {
+                away = this.borderLimit;
+            }
 
 
-        // Intensity
-        var awayX;
-        var awayY;
+            var intensity = 1.0 - (away / this.borderLimit);
+            if (intensity < 0) {
+                return false;
+            }
 
 
-        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 (intensity > 1.0) {
+                intensity = 1.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;
-        }
+            // 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;
 
 
-        var away = (awayX > awayY) ? awayX : awayY;
-        if (away > this.borderLimit) {
-            away = this.borderLimit;
-        }
+            // Effects
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            engine.setDepthBuffer(false);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
 
 
-        var intensity = 1.0 - (away / this.borderLimit);
-        if (intensity < 0) {
-            return false;
-        }
-        
-        if (intensity > 1.0) {
-            intensity = 1.0;
-        }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
 
 
-        // 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_ADD);
-        
-        // VBOs
-        engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, 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);
-            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;
-    };
-
-    BABYLON.LensFlareSystem.prototype.dispose = function () {
-        if (this._vertexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-            this._vertexBuffer = null;
-        }
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
 
 
-        if (this._indexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-            this._indexBuffer = null;
-        }
+                var x = centerX - (distX * flare.position);
+                var y = centerY - (distY * flare.position);
 
 
-        while (this.lensFlares.length) {
-            this.lensFlares[0].dispose();
-        }
+                var cw = flare.size;
+                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
+                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);
 
 
-        // Remove from scene
-        var index = this._scene.lensFlareSystems.indexOf(this);
-        this._scene.lensFlareSystems.splice(index, 1);
-    };
+                // 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 () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = 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);
+        };
+        return LensFlareSystem;
+    })();
+    BABYLON.LensFlareSystem = LensFlareSystem;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.lensFlareSystem.js.map

+ 219 - 0
Babylon/LensFlare/babylon.lensFlareSystem.ts

@@ -0,0 +1,219 @@
+module BABYLON {
+    export class LensFlareSystem {
+        public lensFlares = new Array<LensFlare>();
+        public borderLimit = 300;
+        public meshesSelectionPredicate: (mesh: Mesh) => boolean;
+
+        private _scene: Scene;
+        private _emitter: any;
+        private _vertexDeclaration = [2];
+        private _vertexStrideSize = 2 * 4;
+        private _vertexBuffer: WebGLBuffer;
+        private _indexBuffer: WebGLBuffer;
+        private _effect: Effect;
+        private _positionX: number;
+        private _positionY: number;
+
+        constructor(public name: string, emitter: any, scene: Scene) {
+
+            this._scene = scene;
+            this._emitter = emitter;
+            scene.lensFlareSystems.push(this);
+
+            this.meshesSelectionPredicate = m => m.material && m.isVisible && m.isEnabled() && m.checkCollisions;
+
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("lensFlare",
+                ["position"],
+                ["color", "viewportMatrix"],
+                ["textureSampler"], "");
+        }
+
+        public getScene(): Scene {
+            return this._scene;
+        }
+
+        public getEmitter(): any {
+            return this._emitter;
+        }
+
+        public getEmitterPosition(): Vector3 {
+            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
+        }
+
+        public computeEffectivePosition(globalViewport: Viewport): boolean {
+            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;
+        }
+
+        public _isVisible(): boolean {
+            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;
+        }
+
+        public render(): boolean {
+            if (!this._effect.isReady())
+                return false;
+
+            var engine = this._scene.getEngine();
+            var viewport = this._scene.activeCamera.viewport;
+            var globalViewport = viewport.toGlobal(engine);
+
+            // 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_ADD);
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, 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);
+                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;
+        }
+
+        public dispose(): void {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = 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);
+        }
+    }
+} 

+ 133 - 145
Babylon/Lights/Shadows/babylon.shadowGenerator.js

@@ -1,161 +1,149 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.ShadowGenerator = function (mapSize, light) {
-        this._light = light;
-        this._scene = light.getScene();
-
-        light._shadowGenerator = this;
-
-        // Render target
-        this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
-        this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        this._shadowMap.renderParticles = false;
-
-        // Darkness
-        this._darkness = 0.;
-
-        // Darkness
-        this._transparencyShadow = false;        
-                
-        // Custom render function
-        var that = this;
-
-        var renderSubMesh = function (subMesh) {
-            var mesh = subMesh.getMesh();
-            var world = mesh.getWorldMatrix();
-            var engine = that._scene.getEngine();
-
-            if (that.isReady(mesh)) {
-                engine.enableEffect(that._effect);
-                
-                // Bones
-                if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
-                    that._effect.setMatrix("world", world);
-                    that._effect.setMatrix("viewProjection", that.getTransformMatrix());
-
-                    that._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
-                } else {
-                    world.multiplyToRef(that.getTransformMatrix(), that._worldViewProjection);
-                    that._effect.setMatrix("worldViewProjection", that._worldViewProjection);
+var BABYLON;
+(function (BABYLON) {
+    var ShadowGenerator = (function () {
+        function ShadowGenerator(mapSize, light) {
+            var _this = this;
+            // Members
+            this.useVarianceShadowMap = true;
+            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._light = light;
+            this._scene = light.getScene();
+
+            light._shadowGenerator = this;
+
+            // Render target
+            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
+            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.renderParticles = false;
+
+            // Custom render function
+            var renderSubMesh = function (subMesh) {
+                var mesh = subMesh.getMesh();
+                var world = mesh.getWorldMatrix();
+                var engine = _this._scene.getEngine();
+
+                if (_this.isReady(mesh)) {
+                    engine.enableEffect(_this._effect);
+
+                    // Bones
+                    if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                        _this._effect.setMatrix("world", world);
+                        _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
+
+                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
+                    } else {
+                        world.multiplyToRef(_this.getTransformMatrix(), _this._worldViewProjection);
+                        _this._effect.setMatrix("worldViewProjection", _this._worldViewProjection);
+                    }
+
+                    // Bind and draw
+                    mesh.bindAndDraw(subMesh, _this._effect, false);
                 }
                 }
+            };
 
 
-                // Bind and draw
-                mesh.bindAndDraw(subMesh, that._effect, false);
-            }
-        };
+            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
+                var index;
+
+                for (index = 0; index < opaqueSubMeshes.length; index++) {
+                    renderSubMesh(opaqueSubMeshes.data[index]);
+                }
 
 
-        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]);
+                    }
+                }
+            };
+        }
+        ShadowGenerator.prototype.isReady = function (mesh) {
+            var defines = [];
+
+            if (this.useVarianceShadowMap) {
+                defines.push("#define VSM");
             }
             }
-            
-            for (index = 0; index < alphaTestSubMeshes.length; index++) {
-                renderSubMesh(alphaTestSubMeshes.data[index]);
+
+            var attribs = [BABYLON.VertexBuffer.PositionKind];
+            if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                defines.push("#define BONES");
+                defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
             }
             }
 
 
-            if (that._transparencyShadow) {
-                for (index = 0; index < transparentSubMeshes.length; index++) {
-                    renderSubMesh(transparentSubMeshes.data[index]);
-                }                
+            // 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", "worldViewProjection"], [], join);
             }
             }
+
+            return this._effect.isReady();
         };
         };
-        
-        // Internals
-        this._viewMatrix = BABYLON.Matrix.Zero();
-        this._projectionMatrix = BABYLON.Matrix.Zero();
-        this._transformMatrix = BABYLON.Matrix.Zero();
-        this._worldViewProjection = BABYLON.Matrix.Zero();
-    };
-    
-    // Members
-    BABYLON.ShadowGenerator.prototype.useVarianceShadowMap = true;
-    
-    // Properties
-    BABYLON.ShadowGenerator.prototype.isReady = function (mesh) {
-        var defines = [];
-        
-        if (this.useVarianceShadowMap) {
-            defines.push("#define VSM");
-        }
-        
-        var attribs = [BABYLON.VertexBuffer.PositionKind];
-        if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
-            attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
-            attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
-            defines.push("#define BONES");
-            defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
-        }
 
 
-        // 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", "worldViewProjection"],
-                [], join);
-        }
+        ShadowGenerator.prototype.getShadowMap = function () {
+            return this._shadowMap;
+        };
 
 
-        return this._effect.isReady();
-    };
-    
-    BABYLON.ShadowGenerator.prototype.getShadowMap = function () {
-        return this._shadowMap;
-    };
-    
-    BABYLON.ShadowGenerator.prototype.getLight = function () {
-        return this._light;
-    };
-    
-    // Methods
-    BABYLON.ShadowGenerator.prototype.getTransformMatrix = function () {
-        var lightPosition = this._light.position;
-        var lightDirection = this._light.direction;
-        
-        if (this._light._computeTransformedPosition()) {
-            lightPosition = this._light._transformedPosition;
-        }
+        ShadowGenerator.prototype.getLight = function () {
+            return this._light;
+        };
 
 
-        if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
+        // Methods
+        ShadowGenerator.prototype.getTransformMatrix = function () {
+            var lightPosition = this._light.position;
+            var lightDirection = this._light.direction;
 
 
-            this._cachedPosition = lightPosition.clone();
-            this._cachedDirection = lightDirection.clone();
+            if (this._light._computeTransformedPosition()) {
+                lightPosition = this._light._transformedPosition;
+            }
 
 
-            var activeCamera = this._scene.activeCamera;
+            if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
+                this._cachedPosition = lightPosition.clone();
+                this._cachedDirection = lightDirection.clone();
 
 
-            BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
-            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
+                var activeCamera = this._scene.activeCamera;
 
 
-            this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
-        }
+                BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
+                BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
+
+                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+            }
+
+            return this._transformMatrix;
+        };
 
 
-        return this._transformMatrix;
-    };
-
-    BABYLON.ShadowGenerator.prototype.getDarkness = function () {
-        return this._darkness;
-    };
-
-    BABYLON.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;
-    };
-
-    BABYLON.ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
-        this._transparencyShadow = hasShadow;
-    };
-
-    BABYLON.ShadowGenerator.prototype.dispose = function() {
-        this._shadowMap.dispose();
-    };
-})();
+        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.dispose = function () {
+            this._shadowMap.dispose();
+        };
+        return ShadowGenerator;
+    })();
+    BABYLON.ShadowGenerator = ShadowGenerator;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.shadowGenerator.js.map

+ 161 - 0
Babylon/Lights/Shadows/babylon.shadowGenerator.ts

@@ -0,0 +1,161 @@
+module BABYLON {
+    export class ShadowGenerator {
+        // Members
+        public useVarianceShadowMap = true;
+
+        private _light: DirectionalLight;
+        private _scene: Scene;
+        private _shadowMap: RenderTargetTexture;
+        private _darkness = 0;
+        private _transparencyShadow = false;
+        private _effect: Effect;
+
+        private _viewMatrix = BABYLON.Matrix.Zero();
+        private _projectionMatrix = BABYLON.Matrix.Zero();
+        private _transformMatrix = BABYLON.Matrix.Zero();
+        private _worldViewProjection = BABYLON.Matrix.Zero();
+        private _cachedPosition: Vector3;
+        private _cachedDirection: Vector3;
+        private _cachedDefines: string;
+
+        constructor(mapSize: number, light: DirectionalLight) {
+            this._light = light;
+            this._scene = light.getScene();
+
+            light._shadowGenerator = this;
+
+            // Render target
+            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
+            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.renderParticles = false;
+
+
+            // Custom render function
+            var renderSubMesh = (subMesh: SubMesh): void => {
+                var mesh = subMesh.getMesh();
+                var world = mesh.getWorldMatrix();
+                var engine = this._scene.getEngine();
+
+                if (this.isReady(mesh)) {
+                    engine.enableEffect(this._effect);
+
+                    // Bones
+                    if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                        this._effect.setMatrix("world", world);
+                        this._effect.setMatrix("viewProjection", this.getTransformMatrix());
+
+                        this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
+                    } else {
+                        world.multiplyToRef(this.getTransformMatrix(), this._worldViewProjection);
+                        this._effect.setMatrix("worldViewProjection", this._worldViewProjection);
+                    }
+
+                    // Bind and draw
+                    mesh.bindAndDraw(subMesh, this._effect, false);
+                }
+            };
+
+            this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, transparentSubMeshes: SmartArray): void => {
+                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]);
+                    }
+                }
+            };
+
+        }
+
+        public isReady(mesh: Mesh): boolean {
+            var defines = [];
+
+            if (this.useVarianceShadowMap) {
+                defines.push("#define VSM");
+            }
+
+            var attribs = [BABYLON.VertexBuffer.PositionKind];
+            if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                defines.push("#define BONES");
+                defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
+            }
+
+            // 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", "worldViewProjection"],
+                    [], join);
+            }
+
+            return this._effect.isReady();
+        }
+
+        public getShadowMap(): RenderTargetTexture {
+            return this._shadowMap;
+        }
+
+        public getLight() : DirectionalLight{
+            return this._light;
+        }
+
+        // Methods
+        public getTransformMatrix(): Matrix {
+            var lightPosition = this._light.position;
+            var lightDirection = this._light.direction;
+
+            if (this._light._computeTransformedPosition()) {
+                lightPosition = this._light._transformedPosition;
+            }
+
+            if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
+
+                this._cachedPosition = lightPosition.clone();
+                this._cachedDirection = lightDirection.clone();
+
+                var activeCamera = this._scene.activeCamera;
+
+                BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
+                BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
+
+                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+            }
+
+            return this._transformMatrix;
+        }
+
+        public getDarkness(): number {
+            return this._darkness;
+        }
+
+        public setDarkness(darkness: number): void {
+            if (darkness >= 1.0)
+                this._darkness = 1.0;
+            else if (darkness <= 0.0)
+                this._darkness = 0.0;
+            else
+                this._darkness = darkness;
+        }
+
+        public setTransparencyShadow(hasShadow: boolean): void {
+            this._transparencyShadow = hasShadow;
+        }
+
+        public dispose(): void {
+            this._shadowMap.dispose();
+        }
+    }
+} 

+ 0 - 4
Babylon/Lights/babylon.directionalLight.js

@@ -8,12 +8,9 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var DirectionalLight = (function (_super) {
     var DirectionalLight = (function (_super) {
         __extends(DirectionalLight, _super);
         __extends(DirectionalLight, _super);
-        //ANY
         function DirectionalLight(name, direction, scene) {
         function DirectionalLight(name, direction, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this.direction = direction;
             this.direction = direction;
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
 
 
             this.position = direction.scale(-1);
             this.position = direction.scale(-1);
         }
         }
@@ -35,7 +32,6 @@ var BABYLON;
             return false;
             return false;
         };
         };
 
 
-        //ANY
         DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
         DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
             if (this.parent && this.parent.getWorldMatrix) {
             if (this.parent && this.parent.getWorldMatrix) {
                 if (!this._transformedDirection) {
                 if (!this._transformedDirection) {

+ 3 - 7
Babylon/Lights/babylon.directionalLight.ts

@@ -1,15 +1,12 @@
 module BABYLON {
 module BABYLON {
     export class DirectionalLight extends Light {
     export class DirectionalLight extends Light {
         public position: Vector3;
         public position: Vector3;
-        public diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-        public specular = new BABYLON.Color3(1.0, 1.0, 1.0);
 
 
         private _transformedDirection: Vector3;
         private _transformedDirection: Vector3;
-        private _transformedPosition: Vector3;
+        public _transformedPosition: Vector3;
         private _worldMatrix: Matrix;
         private _worldMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, public direction: Vector3, scene) {
+        constructor(name: string, public direction: Vector3, scene: Scene) {
             super(name, scene);
             super(name, scene);
 
 
             this.position = direction.scale(-1);
             this.position = direction.scale(-1);
@@ -33,8 +30,7 @@
             return false;
             return false;
         }
         }
 
 
-        //ANY
-        public transferToEffect(effect, directionUniformName: string): void {
+        public transferToEffect(effect: Effect, directionUniformName: string): void {
             if (this.parent && this.parent.getWorldMatrix) {
             if (this.parent && this.parent.getWorldMatrix) {
                 if (!this._transformedDirection) {
                 if (!this._transformedDirection) {
                     this._transformedDirection = BABYLON.Vector3.Zero();
                     this._transformedDirection = BABYLON.Vector3.Zero();

+ 0 - 5
Babylon/Lights/babylon.hemisphericLight.js

@@ -8,20 +8,15 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var HemisphericLight = (function (_super) {
     var HemisphericLight = (function (_super) {
         __extends(HemisphericLight, _super);
         __extends(HemisphericLight, _super);
-        //ANY
         function HemisphericLight(name, direction, scene) {
         function HemisphericLight(name, direction, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this.direction = direction;
             this.direction = direction;
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
             this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
             this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
         }
         }
-        //ANY
         HemisphericLight.prototype.getShadowGenerator = function () {
         HemisphericLight.prototype.getShadowGenerator = function () {
             return null;
             return null;
         };
         };
 
 
-        //ANY
         HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
         HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
             var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
             var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
             effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
             effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);

+ 3 - 8
Babylon/Lights/babylon.hemisphericLight.ts

@@ -1,23 +1,18 @@
 module BABYLON {
 module BABYLON {
     export class HemisphericLight extends Light {
     export class HemisphericLight extends Light {
-        public diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-        public specular = new BABYLON.Color3(1.0, 1.0, 1.0);
         public groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
         public groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
 
 
         private _worldMatrix: Matrix;
         private _worldMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, public direction: Vector3, scene) {
+        constructor(name: string, public direction: Vector3, scene: Scene) {
             super(name, scene);
             super(name, scene);
         }
         }
 
 
-        //ANY
-        public getShadowGenerator() {
+        public getShadowGenerator(): ShadowGenerator {
             return null;
             return null;
         }
         }
 
 
-        //ANY
-        public transferToEffect(effect, directionUniformName: string, groundColorUniformName: string): void {
+        public transferToEffect(effect: Effect, directionUniformName: string, groundColorUniformName: string): void {
             var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
             var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
             effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
             effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
             effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
             effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));

+ 3 - 6
Babylon/Lights/babylon.light.js

@@ -8,22 +8,19 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var Light = (function (_super) {
     var Light = (function (_super) {
         __extends(Light, _super);
         __extends(Light, _super);
-        //ANY
         function Light(name, scene) {
         function Light(name, scene) {
             _super.call(this, 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.intensity = 1.0;
+            this.excludedMeshes = new Array();
 
 
             scene.lights.push(this);
             scene.lights.push(this);
-
-            // Exclusions
-            this.excludedMeshes = [];
         }
         }
-        //ANY
         Light.prototype.getShadowGenerator = function () {
         Light.prototype.getShadowGenerator = function () {
             return this._shadowGenerator;
             return this._shadowGenerator;
         };
         };
 
 
-        // ANY
         Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
         Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
         };
         };
 
 

+ 7 - 12
Babylon/Lights/babylon.light.ts

@@ -1,29 +1,24 @@
 module BABYLON {
 module BABYLON {
     export class Light extends Node {
     export class Light extends Node {
+        public diffuse = new Color3(1.0, 1.0, 1.0);
+        public specular = new Color3(1.0, 1.0, 1.0);
         public intensity = 1.0;
         public intensity = 1.0;
-        public animations; //ANY
-        public excludedMeshes; //ANY
+        public excludedMeshes = new Array<Mesh>();
 
 
-        private _shadowGenerator; //ANY
+        public _shadowGenerator: ShadowGenerator;
         private _parentedWorldMatrix: Matrix;
         private _parentedWorldMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, scene) {
+        constructor(name: string, scene: Scene) {
             super(name, scene);
             super(name, scene);
 
 
             scene.lights.push(this);
             scene.lights.push(this);
-
-            // Exclusions
-            this.excludedMeshes = [];
         }
         }
 
 
-        //ANY
-        public getShadowGenerator() {
+        public getShadowGenerator(): ShadowGenerator {
             return this._shadowGenerator;
             return this._shadowGenerator;
         }
         }
 
 
-        // ANY
-        public transferToEffect(effect, uniformName0?: string, uniformName1?: string): void {
+        public transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void {
         }
         }
 
 
         public _getWorldMatrix(): Matrix {
         public _getWorldMatrix(): Matrix {

+ 0 - 5
Babylon/Lights/babylon.pointLight.js

@@ -8,14 +8,10 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var PointLight = (function (_super) {
     var PointLight = (function (_super) {
         __extends(PointLight, _super);
         __extends(PointLight, _super);
-        //ANY
         function PointLight(name, position, scene) {
         function PointLight(name, position, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this.position = position;
             this.position = position;
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
         }
         }
-        //ANY
         PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
         PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
             if (this.parent && this.parent.getWorldMatrix) {
             if (this.parent && this.parent.getWorldMatrix) {
                 if (!this._transformedPosition) {
                 if (!this._transformedPosition) {
@@ -31,7 +27,6 @@ var BABYLON;
             effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
             effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
         };
         };
 
 
-        //ANY
         PointLight.prototype.getShadowGenerator = function () {
         PointLight.prototype.getShadowGenerator = function () {
             return null;
             return null;
         };
         };

+ 3 - 9
Babylon/Lights/babylon.pointLight.ts

@@ -1,18 +1,13 @@
 module BABYLON {
 module BABYLON {
     export class PointLight extends Light {
     export class PointLight extends Light {
-        public diffuse = new Color3(1.0, 1.0, 1.0);
-        public specular = new Color3(1.0, 1.0, 1.0);
-
         private _worldMatrix: Matrix;
         private _worldMatrix: Matrix;
         private _transformedPosition: Vector3;
         private _transformedPosition: Vector3;
 
 
-        //ANY
-        constructor(name: string, public position: Vector3, scene) {
+        constructor(name: string, public position: Vector3, scene: Scene) {
             super(name, scene);
             super(name, scene);
         }
         }
 
 
-        //ANY
-        public transferToEffect(effect, positionUniformName: string): void {
+        public transferToEffect(effect: Effect, positionUniformName: string): void {
             if (this.parent && this.parent.getWorldMatrix) {
             if (this.parent && this.parent.getWorldMatrix) {
                 if (!this._transformedPosition) {
                 if (!this._transformedPosition) {
                     this._transformedPosition = BABYLON.Vector3.Zero();
                     this._transformedPosition = BABYLON.Vector3.Zero();
@@ -27,8 +22,7 @@
             effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
             effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
         }
         }
 
 
-        //ANY
-        public getShadowGenerator() {
+        public getShadowGenerator(): ShadowGenerator {
             return null;
             return null;
         }
         }
 
 

+ 0 - 4
Babylon/Lights/babylon.spotLight.js

@@ -8,22 +8,18 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var SpotLight = (function (_super) {
     var SpotLight = (function (_super) {
         __extends(SpotLight, _super);
         __extends(SpotLight, _super);
-        //ANY
         function SpotLight(name, position, direction, angle, exponent, scene) {
         function SpotLight(name, position, direction, angle, exponent, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this.position = position;
             this.position = position;
             this.direction = direction;
             this.direction = direction;
             this.angle = angle;
             this.angle = angle;
             this.exponent = exponent;
             this.exponent = exponent;
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
         }
         }
         SpotLight.prototype.setDirectionToTarget = function (target) {
         SpotLight.prototype.setDirectionToTarget = function (target) {
             this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
             this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
             return this.direction;
             return this.direction;
         };
         };
 
 
-        //ANY
         SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
         SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
             var normalizeDirection;
             var normalizeDirection;
 
 

+ 2 - 6
Babylon/Lights/babylon.spotLight.ts

@@ -1,14 +1,11 @@
 module BABYLON {
 module BABYLON {
     export class SpotLight extends Light {
     export class SpotLight extends Light {
-        public diffuse = new Color3(1.0, 1.0, 1.0);
-        public specular = new Color3(1.0, 1.0, 1.0);
 
 
         private _transformedDirection: Vector3;
         private _transformedDirection: Vector3;
         private _transformedPosition: Vector3;
         private _transformedPosition: Vector3;
         private _worldMatrix: Matrix;
         private _worldMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, public position: Vector3, public direction: Vector3, public angle: number, public exponent: number, scene) {
+        constructor(name: string, public position: Vector3, public direction: Vector3, public angle: number, public exponent: number, scene: Scene) {
             super(name, scene);
             super(name, scene);
         }
         }
 
 
@@ -17,8 +14,7 @@
             return this.direction;
             return this.direction;
         }
         }
 
 
-        //ANY
-        public transferToEffect(effect, positionUniformName: string, directionUniformName: string): void {
+        public transferToEffect(effect: Effect, positionUniformName: string, directionUniformName: string): void {
             var normalizeDirection;
             var normalizeDirection;
 
 
             if (this.parent && this.parent.getWorldMatrix) {
             if (this.parent && this.parent.getWorldMatrix) {

+ 2 - 2
Babylon/Materials/babylon.effect.ts

@@ -18,7 +18,7 @@
         private _program: WebGLProgram;
         private _program: WebGLProgram;
         private _valueCache = [];
         private _valueCache = [];
 
 
-        constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine, defines?: string, optionalDefines?: string, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
+        constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine, defines?: string, optionalDefines?: string[], onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
             this._engine = engine;
             this._engine = engine;
             this.name = baseName;
             this.name = baseName;
             this.defines = defines;
             this.defines = defines;
@@ -137,7 +137,7 @@
             BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
             BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
         }
         }
 
 
-        public _prepareEffect(vertexSourceCode: string, fragmentSourceCode: string, attributesNames: string[], defines: string, optionalDefines?: string, useFallback?: boolean): void {
+        public _prepareEffect(vertexSourceCode: string, fragmentSourceCode: string, attributesNames: string[], defines: string, optionalDefines?: string[], useFallback?: boolean): void {
             try {
             try {
                 var engine = this._engine;
                 var engine = this._engine;
                 this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
                 this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);

+ 0 - 2
Babylon/Materials/babylon.material.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var Material = (function () {
     var Material = (function () {
-        //ANY
         function Material(name, scene, doNotAdd) {
         function Material(name, scene, doNotAdd) {
             this.name = name;
             this.name = name;
             this.checkReadyOnEveryCall = true;
             this.checkReadyOnEveryCall = true;
@@ -27,7 +26,6 @@
             return this._effect;
             return this._effect;
         };
         };
 
 
-        //ANY
         Material.prototype.getScene = function () {
         Material.prototype.getScene = function () {
             return this._scene;
             return this._scene;
         };
         };

+ 4 - 5
Babylon/Materials/babylon.material.ts

@@ -9,13 +9,13 @@
         public onCompiled: (effect: Effect) => void;
         public onCompiled: (effect: Effect) => void;
         public onError: (effect: Effect, errors: string) => void;
         public onError: (effect: Effect, errors: string) => void;
         public onDispose: () => void;
         public onDispose: () => void;
+        public getRenderTargetTextures: () => SmartArray;
 
 
         public _effect = null;
         public _effect = null;
         public _wasPreviouslyReady = false;
         public _wasPreviouslyReady = false;
-        private _scene; //ANY
+        private _scene: Scene;
 
 
-        //ANY
-        constructor(public name: string, scene, doNotAdd?: boolean) {
+        constructor(public name: string, scene: Scene, doNotAdd?: boolean) {
             this.id = name;
             this.id = name;
 
 
             this._scene = scene;
             this._scene = scene;
@@ -33,8 +33,7 @@
             return this._effect;
             return this._effect;
         }
         }
 
 
-        //ANY
-        public getScene() {
+        public getScene(): Scene {
             return this._scene;
             return this._scene;
         }
         }
 
 

+ 0 - 1
Babylon/Materials/babylon.multiMaterial.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var MultiMaterial = (function (_super) {
     var MultiMaterial = (function (_super) {
         __extends(MultiMaterial, _super);
         __extends(MultiMaterial, _super);
-        //ANY
         function MultiMaterial(name, scene) {
         function MultiMaterial(name, scene) {
             _super.call(this, name, scene, true);
             _super.call(this, name, scene, true);
             this.subMaterials = new Array();
             this.subMaterials = new Array();

+ 1 - 2
Babylon/Materials/babylon.multiMaterial.ts

@@ -2,8 +2,7 @@
     export class MultiMaterial extends Material {
     export class MultiMaterial extends Material {
         public subMaterials = new Array<Material>();
         public subMaterials = new Array<Material>();
 
 
-        //ANY
-        constructor(name: string, scene) {
+        constructor(name: string, scene: Scene) {
             super(name, scene, true);
             super(name, scene, true);
 
 
             scene.multiMaterials.push(this);
             scene.multiMaterials.push(this);

+ 0 - 1
Babylon/Materials/babylon.shaderMaterial.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var ShaderMaterial = (function (_super) {
     var ShaderMaterial = (function (_super) {
         __extends(ShaderMaterial, _super);
         __extends(ShaderMaterial, _super);
-        //ANY
         function ShaderMaterial(name, scene, shaderPath, options) {
         function ShaderMaterial(name, scene, shaderPath, options) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             this._textures = new Array();
             this._textures = new Array();

+ 1 - 2
Babylon/Materials/babylon.shaderMaterial.ts

@@ -12,8 +12,7 @@
         private _matrices = new Array<Matrix>();
         private _matrices = new Array<Matrix>();
         private _cachedWorldViewMatrix = new BABYLON.Matrix();
         private _cachedWorldViewMatrix = new BABYLON.Matrix();
 
 
-        //ANY
-        constructor(name: string, scene, shaderPath: string, options) {
+        constructor(name: string, scene: Scene, shaderPath: string, options) {
             super(name, scene);
             super(name, scene);
             this._shaderPath = shaderPath;
             this._shaderPath = shaderPath;
 
 

+ 12 - 19
Babylon/Materials/babylon.standardMaterial.js

@@ -8,16 +8,9 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var StandardMaterial = (function (_super) {
     var StandardMaterial = (function (_super) {
         __extends(StandardMaterial, _super);
         __extends(StandardMaterial, _super);
-        //ANY
         function StandardMaterial(name, scene) {
         function StandardMaterial(name, scene) {
+            var _this = this;
             _super.call(this, name, scene);
             _super.call(this, name, scene);
-            this.diffuseTexture = null;
-            this.ambientTexture = null;
-            this.opacityTexture = null;
-            this.reflectionTexture = null;
-            this.emissiveTexture = null;
-            this.specularTexture = null;
-            this.bumpTexture = null;
             this.ambientColor = new BABYLON.Color3(0, 0, 0);
             this.ambientColor = new BABYLON.Color3(0, 0, 0);
             this.diffuseColor = new BABYLON.Color3(1, 1, 1);
             this.diffuseColor = new BABYLON.Color3(1, 1, 1);
             this.specularColor = new BABYLON.Color3(1, 1, 1);
             this.specularColor = new BABYLON.Color3(1, 1, 1);
@@ -31,6 +24,16 @@ var BABYLON;
             this._baseColor = new BABYLON.Color3();
             this._baseColor = new BABYLON.Color3();
             this._scaledDiffuse = new BABYLON.Color3();
             this._scaledDiffuse = new BABYLON.Color3();
             this._scaledSpecular = new BABYLON.Color3();
             this._scaledSpecular = new BABYLON.Color3();
+
+            this.getRenderTargetTextures = function () {
+                _this._renderTargets.reset();
+
+                if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
+                    _this._renderTargets.push(_this.reflectionTexture);
+                }
+
+                return _this._renderTargets;
+            };
         }
         }
         StandardMaterial.prototype.needAlphaBlending = function () {
         StandardMaterial.prototype.needAlphaBlending = function () {
             return (this.alpha < 1.0) || (this.opacityTexture != null);
             return (this.alpha < 1.0) || (this.opacityTexture != null);
@@ -58,7 +61,7 @@ var BABYLON;
 
 
             var engine = scene.getEngine();
             var engine = scene.getEngine();
             var defines = [];
             var defines = [];
-            var optionalDefines = [];
+            var optionalDefines = new Array();
 
 
             // Textures
             // Textures
             if (scene.texturesEnabled) {
             if (scene.texturesEnabled) {
@@ -257,16 +260,6 @@ var BABYLON;
             return true;
             return true;
         };
         };
 
 
-        StandardMaterial.prototype.getRenderTargetTextures = function () {
-            this._renderTargets.reset();
-
-            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
-                this._renderTargets.push(this.reflectionTexture);
-            }
-
-            return this._renderTargets;
-        };
-
         StandardMaterial.prototype.unbind = function () {
         StandardMaterial.prototype.unbind = function () {
             if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
             if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
                 this._effect.setTexture("reflection2DSampler", null);
                 this._effect.setTexture("reflection2DSampler", null);

+ 35 - 35
Babylon/Materials/babylon.standardMaterial.ts

@@ -1,12 +1,12 @@
 module BABYLON {
 module BABYLON {
     export class StandardMaterial extends Material {
     export class StandardMaterial extends Material {
-        public diffuseTexture = null;
-        public ambientTexture = null;
-        public opacityTexture = null;
-        public reflectionTexture = null;
-        public emissiveTexture = null;
-        public specularTexture = null;
-        public bumpTexture = null;
+        public diffuseTexture: Texture;
+        public ambientTexture: Texture;
+        public opacityTexture: Texture;
+        public reflectionTexture: Texture;
+        public emissiveTexture: Texture;
+        public specularTexture: Texture;
+        public bumpTexture: Texture;
 
 
         public ambientColor = new BABYLON.Color3(0, 0, 0);
         public ambientColor = new BABYLON.Color3(0, 0, 0);
         public diffuseColor = new BABYLON.Color3(1, 1, 1);
         public diffuseColor = new BABYLON.Color3(1, 1, 1);
@@ -24,9 +24,18 @@
         private _scaledSpecular = new BABYLON.Color3();
         private _scaledSpecular = new BABYLON.Color3();
         private _renderId: number;
         private _renderId: number;
 
 
-        //ANY
-        constructor(name: string, scene) {
+        constructor(name: string, scene: Scene) {
             super(name, scene);
             super(name, scene);
+
+            this.getRenderTargetTextures = (): SmartArray => {
+                this._renderTargets.reset();
+
+                if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
+                    this._renderTargets.push(this.reflectionTexture);
+                }
+
+                return this._renderTargets;
+            }
         }
         }
 
 
         public needAlphaBlending(): boolean {
         public needAlphaBlending(): boolean {
@@ -48,14 +57,14 @@
             var scene = this.getScene();
             var scene = this.getScene();
 
 
             if (!this.checkReadyOnEveryCall) {
             if (!this.checkReadyOnEveryCall) {
-                if (this._renderId ===scene.getRenderId()) {
+                if (this._renderId === scene.getRenderId()) {
                     return true;
                     return true;
                 }
                 }
             }
             }
 
 
-            var engine =scene.getEngine();
+            var engine = scene.getEngine();
             var defines = [];
             var defines = [];
-            var optionalDefines = [];
+            var optionalDefines = new Array<string>();
 
 
             // Textures
             // Textures
             if (scene.texturesEnabled) {
             if (scene.texturesEnabled) {
@@ -136,8 +145,8 @@
             var shadowsActivated = false;
             var shadowsActivated = false;
             var lightIndex = 0;
             var lightIndex = 0;
             if (scene.lightsEnabled) {
             if (scene.lightsEnabled) {
-                for (var index = 0; index <scene.lights.length; index++) {
-                    var light =scene.lights[index];
+                for (var index = 0; index < scene.lights.length; index++) {
+                    var light = scene.lights[index];
 
 
                     if (!light.isEnabled()) {
                     if (!light.isEnabled()) {
                         continue;
                         continue;
@@ -230,7 +239,7 @@
                     shaderName = "legacydefault";
                     shaderName = "legacydefault";
                 }
                 }
 
 
-                this._effect =scene.getEngine().createEffect(shaderName,
+                this._effect = scene.getEngine().createEffect(shaderName,
                     attribs,
                     attribs,
                     ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
                     ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
                         "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
                         "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
@@ -251,20 +260,11 @@
                 return false;
                 return false;
             }
             }
 
 
-            this._renderId =scene.getRenderId();
+            this._renderId = scene.getRenderId();
             this._wasPreviouslyReady = true;
             this._wasPreviouslyReady = true;
             return true;
             return true;
         }
         }
 
 
-        public getRenderTargetTextures(): SmartArray {
-            this._renderTargets.reset();
-
-            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
-                this._renderTargets.push(this.reflectionTexture);
-            }
-
-            return this._renderTargets;
-        }
 
 
         public unbind(): void {
         public unbind(): void {
             if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
             if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
@@ -278,7 +278,7 @@
 
 
             // Matrices        
             // Matrices        
             this._effect.setMatrix("world", world);
             this._effect.setMatrix("world", world);
-            this._effect.setMatrix("viewProjection",scene.getTransformMatrix());
+            this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
 
 
             // Bones
             // Bones
             if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
             if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
@@ -334,7 +334,7 @@
                 this._effect.setMatrix("specularMatrix", this.specularTexture._computeTextureMatrix());
                 this._effect.setMatrix("specularMatrix", this.specularTexture._computeTextureMatrix());
             }
             }
 
 
-            if (this.bumpTexture &&scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
+            if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
                 this._effect.setTexture("bumpSampler", this.bumpTexture);
                 this._effect.setTexture("bumpSampler", this.bumpTexture);
 
 
                 this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
                 this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
@@ -342,9 +342,9 @@
             }
             }
 
 
             // Colors
             // Colors
-           scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
+            scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
 
 
-            this._effect.setVector3("vEyePosition",scene.activeCamera.position);
+            this._effect.setVector3("vEyePosition", scene.activeCamera.position);
             this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
             this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
             this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
             this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
             this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
             this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
@@ -352,8 +352,8 @@
 
 
             if (scene.lightsEnabled) {
             if (scene.lightsEnabled) {
                 var lightIndex = 0;
                 var lightIndex = 0;
-                for (var index = 0; index <scene.lights.length; index++) {
-                    var light =scene.lights[index];
+                for (var index = 0; index < scene.lights.length; index++) {
+                    var light = scene.lights[index];
 
 
                     if (!light.isEnabled()) {
                     if (!light.isEnabled()) {
                         continue;
                         continue;
@@ -399,19 +399,19 @@
             }
             }
 
 
             if (scene.clipPlane) {
             if (scene.clipPlane) {
-                var clipPlane =scene.clipPlane;
+                var clipPlane = scene.clipPlane;
                 this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
                 this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
             }
             }
 
 
             // View
             // View
             if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
             if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
-                this._effect.setMatrix("view",scene.getViewMatrix());
+                this._effect.setMatrix("view", scene.getViewMatrix());
             }
             }
 
 
             // Fog
             // Fog
             if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
             if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-                this._effect.setFloat4("vFogInfos",scene.fogMode,scene.fogStart,scene.fogEnd,scene.fogDensity);
-                this._effect.setColor3("vFogColor",scene.fogColor);
+                this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
+                this._effect.setColor3("vFogColor", scene.fogColor);
             }
             }
         }
         }
 
 

+ 2 - 7
Babylon/Materials/textures/babylon.baseTexture.js

@@ -1,28 +1,24 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var BaseTexture = (function () {
     var BaseTexture = (function () {
-        //ANY
         function BaseTexture(scene) {
         function BaseTexture(scene) {
-            this.delayLoadState = 0;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
             this.hasAlpha = false;
             this.hasAlpha = false;
             this.level = 1;
             this.level = 1;
             this.isCube = false;
             this.isCube = false;
-            this._texture = null;
             this._scene = scene;
             this._scene = scene;
             this._scene.textures.push(this);
             this._scene.textures.push(this);
         }
         }
-        //ANY
         BaseTexture.prototype.getScene = function () {
         BaseTexture.prototype.getScene = function () {
             return this._scene;
             return this._scene;
         };
         };
 
 
-        //ANY
         BaseTexture.prototype.getInternalTexture = function () {
         BaseTexture.prototype.getInternalTexture = function () {
             return this._texture;
             return this._texture;
         };
         };
 
 
         BaseTexture.prototype.isReady = function () {
         BaseTexture.prototype.isReady = function () {
-            if (this.delayLoadState === 4) {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return true;
                 return true;
             }
             }
 
 
@@ -56,7 +52,6 @@
             return { width: this._texture._baseWidth, height: this._texture._baseHeight };
             return { width: this._texture._baseWidth, height: this._texture._baseHeight };
         };
         };
 
 
-        //ANY
         BaseTexture.prototype._getFromCache = function (url, noMipmap) {
         BaseTexture.prototype._getFromCache = function (url, noMipmap) {
             var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
             var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
             for (var index = 0; index < texturesCache.length; index++) {
             for (var index = 0; index < texturesCache.length; index++) {

+ 9 - 13
Babylon/Materials/textures/babylon.baseTexture.ts

@@ -1,32 +1,29 @@
 module BABYLON {
 module BABYLON {
     export class BaseTexture {
     export class BaseTexture {
-        public delayLoadState = 0; //ANY BABYLON.Engine.DELAYLOADSTATE_NONE;
+        public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
         public hasAlpha = false;
         public hasAlpha = false;
         public level = 1;
         public level = 1;
         public isCube = false;
         public isCube = false;
-        public _texture = null; //ANY
+        public _texture: WebGLTexture;
         public onDispose: () => void;
         public onDispose: () => void;
 
 
-        private _scene; //ANY
+        private _scene: Scene;
 
 
-        //ANY
-        constructor(scene) {
+        constructor(scene: Scene) {
             this._scene = scene;
             this._scene = scene;
             this._scene.textures.push(this);
             this._scene.textures.push(this);
         }
         }
 
 
-        //ANY
-        public getScene() {
+        public getScene(): Scene {
             return this._scene;
             return this._scene;
-        }
+        } 
 
 
-        //ANY
-        public getInternalTexture() {
+        public getInternalTexture(): WebGLTexture {
             return this._texture;
             return this._texture;
         }
         }
 
 
         public isReady(): boolean {
         public isReady(): boolean {
-            if (this.delayLoadState === 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return true;
                 return true;
             }
             }
 
 
@@ -60,8 +57,7 @@
             return { width: this._texture._baseWidth, height: this._texture._baseHeight };
             return { width: this._texture._baseWidth, height: this._texture._baseHeight };
         }
         }
 
 
-        //ANY
-        public _getFromCache(url: string, noMipmap: boolean) {
+        public _getFromCache(url: string, noMipmap: boolean): WebGLTexture {
             var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
             var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
             for (var index = 0; index < texturesCache.length; index++) {
             for (var index = 0; index < texturesCache.length; index++) {
                 var texturesCacheEntry = texturesCache[index];
                 var texturesCacheEntry = texturesCache[index];

+ 3 - 4
Babylon/Materials/textures/babylon.cubeTexture.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var CubeTexture = (function (_super) {
     var CubeTexture = (function (_super) {
         __extends(CubeTexture, _super);
         __extends(CubeTexture, _super);
-        //ANY
         function CubeTexture(rootUrl, scene, extensions, noMipmap) {
         function CubeTexture(rootUrl, scene, extensions, noMipmap) {
             _super.call(this, scene);
             _super.call(this, scene);
             this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
             this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
@@ -30,7 +29,7 @@ var BABYLON;
                 if (!scene.useDelayedTextureLoading) {
                 if (!scene.useDelayedTextureLoading) {
                     this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
                     this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
                 } else {
                 } else {
-                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                 }
                 }
             }
             }
 
 
@@ -40,11 +39,11 @@ var BABYLON;
         }
         }
         // Methods
         // Methods
         CubeTexture.prototype.delayLoad = function () {
         CubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState != 4) {
+            if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return;
                 return;
             }
             }
 
 
-            this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
             this._texture = this._getFromCache(this.url, this._noMipmap);
             this._texture = this._getFromCache(this.url, this._noMipmap);
 
 
             if (!this._texture) {
             if (!this._texture) {

+ 4 - 5
Babylon/Materials/textures/babylon.cubeTexture.ts

@@ -8,8 +8,7 @@
         private _extensions: string[];
         private _extensions: string[];
         private _textureMatrix: Matrix;
         private _textureMatrix: Matrix;
 
 
-        //ANY
-        constructor(rootUrl: string, scene, extensions: string[], noMipmap?: boolean) {
+        constructor(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean) {
             super(scene);
             super(scene);
 
 
             this.name = rootUrl;
             this.name = rootUrl;
@@ -29,7 +28,7 @@
                 if (!scene.useDelayedTextureLoading) {
                 if (!scene.useDelayedTextureLoading) {
                     this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
                     this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
                 } else {
                 } else {
-                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                 }
                 }
             }
             }
 
 
@@ -40,11 +39,11 @@
 
 
         // Methods
         // Methods
         public delayLoad(): void {
         public delayLoad(): void {
-            if (this.delayLoadState != 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+            if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return;
                 return;
             }
             }
 
 
-            this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
             this._texture = this._getFromCache(this.url, this._noMipmap);
             this._texture = this._getFromCache(this.url, this._noMipmap);
 
 
             if (!this._texture) {
             if (!this._texture) {

+ 1 - 2
Babylon/Materials/textures/babylon.mirrorTexture.js

@@ -8,10 +8,9 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var MirrorTexture = (function (_super) {
     var MirrorTexture = (function (_super) {
         __extends(MirrorTexture, _super);
         __extends(MirrorTexture, _super);
-        //ANY
         function MirrorTexture(name, size, scene, generateMipMaps) {
         function MirrorTexture(name, size, scene, generateMipMaps) {
             var _this = this;
             var _this = this;
-            _super.call(this, name, size, scene, generateMipMaps);
+            _super.call(this, name, size, scene, generateMipMaps, true);
             this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
             this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
             this._transformMatrix = BABYLON.Matrix.Zero();
             this._transformMatrix = BABYLON.Matrix.Zero();
             this._mirrorMatrix = BABYLON.Matrix.Zero();
             this._mirrorMatrix = BABYLON.Matrix.Zero();

+ 2 - 3
Babylon/Materials/textures/babylon.mirrorTexture.ts

@@ -6,9 +6,8 @@
         private _mirrorMatrix = BABYLON.Matrix.Zero();
         private _mirrorMatrix = BABYLON.Matrix.Zero();
         private _savedViewMatrix: Matrix;
         private _savedViewMatrix: Matrix;
 
 
-        //ANY
-        constructor(name: string, size: number, scene, generateMipMaps?: boolean) {
-            super(name, size, scene, generateMipMaps);
+        constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean) {
+            super(name, size, scene, generateMipMaps, true);
 
 
             this.onBeforeRender = () => {
             this.onBeforeRender = () => {
                 BABYLON.Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix);
                 BABYLON.Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix);

+ 19 - 11
Babylon/Materials/textures/babylon.renderTargetTexture.js

@@ -8,34 +8,34 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var RenderTargetTexture = (function (_super) {
     var RenderTargetTexture = (function (_super) {
         __extends(RenderTargetTexture, _super);
         __extends(RenderTargetTexture, _super);
-        //ANY
-        function RenderTargetTexture(name, size, scene, generateMipMaps) {
+        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectratio) {
             _super.call(this, null, scene, !generateMipMaps);
             _super.call(this, null, scene, !generateMipMaps);
             this.renderList = new Array();
             this.renderList = new Array();
             this.renderParticles = true;
             this.renderParticles = true;
             this.renderSprites = false;
             this.renderSprites = false;
-            this.isRenderTarget = true;
             this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
             this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
 
 
             this.name = name;
             this.name = name;
+            this.isRenderTarget = true;
             this._size = size;
             this._size = size;
             this._generateMipMaps = generateMipMaps;
             this._generateMipMaps = generateMipMaps;
+            this._doNotChangeAspectratio = doNotChangeAspectratio;
 
 
             this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
             this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
 
 
             // Rendering groups
             // Rendering groups
             this._renderingManager = new BABYLON.RenderingManager(scene);
             this._renderingManager = new BABYLON.RenderingManager(scene);
         }
         }
+        RenderTargetTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+
         RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
         RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
             this.releaseInternalTexture();
             this.releaseInternalTexture();
             this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
             this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
         };
         };
 
 
         RenderTargetTexture.prototype.render = function () {
         RenderTargetTexture.prototype.render = function () {
-            if (this.onBeforeRender) {
-                this.onBeforeRender();
-            }
-
             var scene = this.getScene();
             var scene = this.getScene();
             var engine = scene.getEngine();
             var engine = scene.getEngine();
 
 
@@ -50,9 +50,6 @@ var BABYLON;
             }
             }
 
 
             if (!this.renderList || this.renderList.length == 0) {
             if (!this.renderList || this.renderList.length == 0) {
-                if (this.onAfterRender) {
-                    this.onAfterRender();
-                }
                 return;
                 return;
             }
             }
 
 
@@ -76,16 +73,27 @@ var BABYLON;
                 }
                 }
             }
             }
 
 
+            if (!this._doNotChangeAspectratio) {
+                scene.updateTransformMatrix(true);
+            }
+
+            if (this.onBeforeRender) {
+                this.onBeforeRender();
+            }
+
             // Render
             // Render
             this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
             this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
 
 
-            //Call this before unBinding Framebuffer in case of manipulating texture with WebGL commands inside the onAfterRender method.
             if (this.onAfterRender) {
             if (this.onAfterRender) {
                 this.onAfterRender();
                 this.onAfterRender();
             }
             }
 
 
             // Unbind
             // Unbind
             engine.unBindFramebuffer(this._texture);
             engine.unBindFramebuffer(this._texture);
+
+            if (!this._doNotChangeAspectratio) {
+                scene.updateTransformMatrix(true);
+            }
         };
         };
 
 
         RenderTargetTexture.prototype.clone = function () {
         RenderTargetTexture.prototype.clone = function () {

+ 22 - 14
Babylon/Materials/textures/babylon.renderTargetTexture.ts

@@ -3,24 +3,25 @@
         public renderList = new Array<Mesh>();
         public renderList = new Array<Mesh>();
         public renderParticles = true;
         public renderParticles = true;
         public renderSprites = false;
         public renderSprites = false;
-        public isRenderTarget = true;
         public coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
         public coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
         public onBeforeRender: () => void;
         public onBeforeRender: () => void;
         public onAfterRender: () => void;
         public onAfterRender: () => void;
-        public customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents: () => void) => void;
+        public customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents?: () => void) => void;
 
 
         private _size: number;
         private _size: number;
         public _generateMipMaps: boolean;
         public _generateMipMaps: boolean;
         private _renderingManager
         private _renderingManager
-        public _waitingRenderList: number[];
+        public _waitingRenderList: string[];
+        private _doNotChangeAspectratio: boolean;
 
 
-        //ANY
-        constructor(name: string, size: number, scene, generateMipMaps?: boolean) {
+        constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean, doNotChangeAspectratio?: boolean) {
             super(null, scene, !generateMipMaps);
             super(null, scene, !generateMipMaps);
 
 
             this.name = name;
             this.name = name;
+            this.isRenderTarget = true;
             this._size = size;
             this._size = size;
             this._generateMipMaps = generateMipMaps;
             this._generateMipMaps = generateMipMaps;
+            this._doNotChangeAspectratio = doNotChangeAspectratio;
 
 
             this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
             this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
 
 
@@ -28,17 +29,16 @@
             this._renderingManager = new BABYLON.RenderingManager(scene);
             this._renderingManager = new BABYLON.RenderingManager(scene);
         }
         }
 
 
+        public getRenderSize(): number {
+            return this._size;
+        }
+
         public resize(size, generateMipMaps) {
         public resize(size, generateMipMaps) {
             this.releaseInternalTexture();
             this.releaseInternalTexture();
             this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
             this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
         }
         }
 
 
         public render() {
         public render() {
-
-            if (this.onBeforeRender) {
-                this.onBeforeRender();
-            }
-
             var scene = this.getScene();
             var scene = this.getScene();
             var engine = scene.getEngine();
             var engine = scene.getEngine();
 
 
@@ -53,9 +53,6 @@
             }
             }
 
 
             if (!this.renderList || this.renderList.length == 0) {
             if (!this.renderList || this.renderList.length == 0) {
-                if (this.onAfterRender) {
-                    this.onAfterRender();
-                }
                 return;
                 return;
             }
             }
 
 
@@ -79,16 +76,27 @@
                 }
                 }
             }
             }
 
 
+            if (!this._doNotChangeAspectratio) {
+                scene.updateTransformMatrix(true);
+            }
+
+            if (this.onBeforeRender) {
+                this.onBeforeRender();
+            }
+
             // Render
             // Render
             this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
             this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
 
 
-            //Call this before unBinding Framebuffer in case of manipulating texture with WebGL commands inside the onAfterRender method.
             if (this.onAfterRender) {
             if (this.onAfterRender) {
                 this.onAfterRender();
                 this.onAfterRender();
             }
             }
 
 
             // Unbind
             // Unbind
             engine.unBindFramebuffer(this._texture);
             engine.unBindFramebuffer(this._texture);
+
+            if (!this._doNotChangeAspectratio) {
+                scene.updateTransformMatrix(true);
+            }
         }
         }
 
 
         public clone(): RenderTargetTexture {
         public clone(): RenderTargetTexture {

+ 4 - 4
Babylon/Materials/textures/babylon.texture.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var Texture = (function (_super) {
     var Texture = (function (_super) {
         __extends(Texture, _super);
         __extends(Texture, _super);
-        //ANY
         function Texture(url, scene, noMipmap, invertY) {
         function Texture(url, scene, noMipmap, invertY) {
             _super.call(this, scene);
             _super.call(this, scene);
             this.uOffset = 0;
             this.uOffset = 0;
@@ -24,6 +23,7 @@ var BABYLON;
             this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
             this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
             this.anisotropicFilteringLevel = 4;
             this.anisotropicFilteringLevel = 4;
             this.animations = new Array();
             this.animations = new Array();
+            this.isRenderTarget = false;
 
 
             this.name = url;
             this.name = url;
             this.url = url;
             this.url = url;
@@ -40,16 +40,16 @@ var BABYLON;
                 if (!scene.useDelayedTextureLoading) {
                 if (!scene.useDelayedTextureLoading) {
                     this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
                     this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
                 } else {
                 } else {
-                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                 }
                 }
             }
             }
         }
         }
         Texture.prototype.delayLoad = function () {
         Texture.prototype.delayLoad = function () {
-            if (this.delayLoadState != 4) {
+            if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return;
                 return;
             }
             }
 
 
-            this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
             this._texture = this._getFromCache(this.url, this._noMipmap);
             this._texture = this._getFromCache(this.url, this._noMipmap);
 
 
             if (!this._texture) {
             if (!this._texture) {

+ 7 - 7
Babylon/Materials/textures/babylon.texture.ts

@@ -32,6 +32,7 @@
         public coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
         public coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
         public anisotropicFilteringLevel = 4;
         public anisotropicFilteringLevel = 4;
         public animations = new Array<Animation>();
         public animations = new Array<Animation>();
+        public isRenderTarget = false;
 
 
         private _noMipmap: boolean;
         private _noMipmap: boolean;
         public _invertY: boolean;
         public _invertY: boolean;
@@ -52,8 +53,7 @@
         private _cachedWAng: number;
         private _cachedWAng: number;
         private _cachedCoordinatesMode: number;
         private _cachedCoordinatesMode: number;
 
 
-        //ANY
-        constructor(url: string, scene, noMipmap?: boolean, invertY?: boolean) {
+        constructor(url: string, scene: Scene, noMipmap?: boolean, invertY?: boolean) {
             super(scene);
             super(scene);
 
 
             this.name = url;
             this.name = url;
@@ -71,17 +71,17 @@
                 if (!scene.useDelayedTextureLoading) {
                 if (!scene.useDelayedTextureLoading) {
                     this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
                     this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
                 } else {
                 } else {
-                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                 }
                 }
             }
             }
         }
         }
 
 
         public delayLoad(): void {
         public delayLoad(): void {
-            if (this.delayLoadState != 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+            if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                 return;
                 return;
             }
             }
 
 
-            this.delayLoadState = 1;//ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
             this._texture = this._getFromCache(this.url, this._noMipmap);
             this._texture = this._getFromCache(this.url, this._noMipmap);
 
 
             if (!this._texture) {
             if (!this._texture) {
@@ -104,7 +104,7 @@
             t.z += 0.5;
             t.z += 0.5;
         }
         }
 
 
-        private _computeTextureMatrix(): Matrix {
+        public _computeTextureMatrix(): Matrix {
             if (
             if (
                 this.uOffset === this._cachedUOffset &&
                 this.uOffset === this._cachedUOffset &&
                 this.vOffset === this._cachedVOffset &&
                 this.vOffset === this._cachedVOffset &&
@@ -149,7 +149,7 @@
             return this._cachedTextureMatrix;
             return this._cachedTextureMatrix;
         }
         }
 
 
-        private _computeReflectionTextureMatrix(): Matrix {
+        public _computeReflectionTextureMatrix(): Matrix {
             if (
             if (
                 this.uOffset === this._cachedUOffset &&
                 this.uOffset === this._cachedUOffset &&
                 this.vOffset === this._cachedVOffset &&
                 this.vOffset === this._cachedVOffset &&

+ 1 - 5
Babylon/Math/babylon.math.js

@@ -1936,11 +1936,7 @@
                 return null;
                 return null;
             }
             }
 
 
-            return {
-                bu: bu,
-                bv: bv,
-                distance: Vector3.Dot(this._edge2, this._qvec) * invdet
-            };
+            return new IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
         };
         };
 
 
         // Statics
         // Statics

+ 2 - 6
Babylon/Math/babylon.math.ts

@@ -1927,7 +1927,7 @@
             return temp <= rr;
             return temp <= rr;
         }
         }
 
 
-        public intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3) {
+        public intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo {
             if (!this._edge1) {
             if (!this._edge1) {
                 this._edge1 = BABYLON.Vector3.Zero();
                 this._edge1 = BABYLON.Vector3.Zero();
                 this._edge2 = BABYLON.Vector3.Zero();
                 this._edge2 = BABYLON.Vector3.Zero();
@@ -1963,11 +1963,7 @@
                 return null;
                 return null;
             }
             }
 
 
-            return {
-                bu: bu,
-                bv: bv,
-                distance: Vector3.Dot(this._edge2, this._qvec) * invdet
-            };
+            return new IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
         }
         }
 
 
         // Statics
         // Statics

+ 0 - 2
Babylon/Mesh/babylon.csg.js

@@ -403,7 +403,6 @@
 
 
         // Build Raw mesh from CSG
         // Build Raw mesh from CSG
         // Coordinates here are in world space
         // Coordinates here are in world space
-        //ANY
         CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
         CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
             var matrix = this.matrix.clone();
             var matrix = this.matrix.clone();
             matrix.invert();
             matrix.invert();
@@ -496,7 +495,6 @@
         };
         };
 
 
         // Build Mesh from CSG taking material and transforms into account
         // Build Mesh from CSG taking material and transforms into account
-        //ANY
         CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
         CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
             var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
             var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
 
 

+ 2 - 4
Babylon/Mesh/babylon.csg.ts

@@ -401,8 +401,7 @@
 
 
         // Build Raw mesh from CSG
         // Build Raw mesh from CSG
         // Coordinates here are in world space
         // Coordinates here are in world space
-        //ANY
-        public buildMeshGeometry(name: string, scene, keepSubMeshes: boolean): Mesh {
+        public buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh {
             var matrix = this.matrix.clone();
             var matrix = this.matrix.clone();
             matrix.invert();
             matrix.invert();
 
 
@@ -517,8 +516,7 @@
         }
         }
 
 
         // Build Mesh from CSG taking material and transforms into account
         // Build Mesh from CSG taking material and transforms into account
-        //ANY
-        public toMesh(name: string, material, scene, keepSubMeshes: boolean): Mesh {
+        public toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh {
             var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
             var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
 
 
             mesh.material = material;
             mesh.material = material;

+ 18 - 74
Babylon/Mesh/babylon.mesh.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var Mesh = (function (_super) {
     var Mesh = (function (_super) {
         __extends(Mesh, _super);
         __extends(Mesh, _super);
-        //ANY
         function Mesh(name, scene) {
         function Mesh(name, scene) {
             _super.call(this, name, scene);
             _super.call(this, name, scene);
             // Members
             // Members
@@ -16,7 +15,7 @@ var BABYLON;
             this.rotation = new BABYLON.Vector3(0, 0, 0);
             this.rotation = new BABYLON.Vector3(0, 0, 0);
             this.rotationQuaternion = null;
             this.rotationQuaternion = null;
             this.scaling = new BABYLON.Vector3(1, 1, 1);
             this.scaling = new BABYLON.Vector3(1, 1, 1);
-            this.delayLoadState = 0;
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
             this.material = null;
             this.material = null;
             this.isVisible = true;
             this.isVisible = true;
             this.isPickable = true;
             this.isPickable = true;
@@ -342,7 +341,7 @@ var BABYLON;
                     zero = this.getScene().activeCamera.position;
                     zero = this.getScene().activeCamera.position;
                 } else {
                 } else {
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
-                        zero.x = localPosition.x + 0.001; //ANY:BABYLON.Engine.epsilon
+                        zero.x = localPosition.x + BABYLON.Engine.Epsilon;
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
                         zero.y = localPosition.y + 0.001;
                         zero.y = localPosition.y + 0.001;
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
@@ -517,9 +516,8 @@ var BABYLON;
             effectiveMaterial.unbind();
             effectiveMaterial.unbind();
         };
         };
 
 
-        //ANY
         Mesh.prototype.getEmittedParticleSystems = function () {
         Mesh.prototype.getEmittedParticleSystems = function () {
-            var results = [];
+            var results = new Array();
             for (var index = 0; index < this.getScene().particleSystems.length; index++) {
             for (var index = 0; index < this.getScene().particleSystems.length; index++) {
                 var particleSystem = this.getScene().particleSystems[index];
                 var particleSystem = this.getScene().particleSystems[index];
                 if (particleSystem.emitter === this) {
                 if (particleSystem.emitter === this) {
@@ -530,9 +528,8 @@ var BABYLON;
             return results;
             return results;
         };
         };
 
 
-        //ANY
         Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
         Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
-            var results = [];
+            var results = new Array();
             var descendants = this.getDescendants();
             var descendants = this.getDescendants();
             descendants.push(this);
             descendants.push(this);
 
 
@@ -560,19 +557,19 @@ var BABYLON;
 
 
         Mesh.prototype.isInFrustum = function (frustumPlanes) {
         Mesh.prototype.isInFrustum = function (frustumPlanes) {
             var _this = this;
             var _this = this;
-            if (this.delayLoadState === 2) {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                 return false;
                 return false;
             }
             }
 
 
             var result = this._boundingInfo.isInFrustum(frustumPlanes);
             var result = this._boundingInfo.isInFrustum(frustumPlanes);
 
 
-            if (result && this.delayLoadState === 4) {
-                this.delayLoadState = 2; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADING
+            if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
                 this.getScene()._addPendingData(this);
                 this.getScene()._addPendingData(this);
 
 
                 BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
                 BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
                     _this._delayLoadingFunction(JSON.parse(data), _this);
                     _this._delayLoadingFunction(JSON.parse(data), _this);
-                    _this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+                    _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
                     _this.getScene()._removePendingData(_this);
                     _this.getScene()._removePendingData(_this);
                 }, function () {
                 }, function () {
                 }, this.getScene().database);
                 }, this.getScene().database);
@@ -921,7 +918,9 @@ var BABYLON;
 
 
         // Physics
         // Physics
         Mesh.prototype.setPhysicsState = function (options) {
         Mesh.prototype.setPhysicsState = function (options) {
-            if (!this.getScene()._physicsEngine) {
+            var physicsEngine = this.getScene().getPhysicsEngine();
+
+            if (!physicsEngine) {
                 return;
                 return;
             }
             }
 
 
@@ -936,11 +935,11 @@ var BABYLON;
             this._physicRestitution = options.restitution;
             this._physicRestitution = options.restitution;
 
 
             if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
             if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
-                this.getScene()._physicsEngine._unregisterMesh(this);
+                physicsEngine._unregisterMesh(this);
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._registerMesh(this, options);
+            physicsEngine._registerMesh(this, options);
         };
         };
 
 
         Mesh.prototype.getPhysicsImpostor = function () {
         Mesh.prototype.getPhysicsImpostor = function () {
@@ -980,7 +979,7 @@ var BABYLON;
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._applyImpulse(this, force, contactPoint);
+            this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
         };
         };
 
 
         Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
         Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
@@ -988,7 +987,7 @@ var BABYLON;
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
+            this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
         };
         };
 
 
         // Geometric tools
         // Geometric tools
@@ -1074,7 +1073,6 @@ var BABYLON;
         };
         };
 
 
         // Statics
         // Statics
-        //ANY
         Mesh.CreateBox = function (name, size, scene, updatable) {
         Mesh.CreateBox = function (name, size, scene, updatable) {
             var box = new BABYLON.Mesh(name, scene);
             var box = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateBox(size);
             var vertexData = BABYLON.VertexData.CreateBox(size);
@@ -1084,7 +1082,6 @@ var BABYLON;
             return box;
             return box;
         };
         };
 
 
-        //ANY
         Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
         Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
             var sphere = new BABYLON.Mesh(name, scene);
             var sphere = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
             var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
@@ -1095,7 +1092,6 @@ var BABYLON;
         };
         };
 
 
         // Cylinder and cone (Code inspired by SharpDX.org)
         // Cylinder and cone (Code inspired by SharpDX.org)
-        //ANY
         Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
         Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
             var cylinder = new BABYLON.Mesh(name, scene);
             var cylinder = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
             var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
@@ -1106,7 +1102,6 @@ var BABYLON;
         };
         };
 
 
         // Torus  (Code from SharpDX.org)
         // Torus  (Code from SharpDX.org)
-        //ANY
         Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
         Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
             var torus = new BABYLON.Mesh(name, scene);
             var torus = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
             var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
@@ -1116,7 +1111,6 @@ var BABYLON;
             return torus;
             return torus;
         };
         };
 
 
-        //ANY
         Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
         Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
             var torusKnot = new BABYLON.Mesh(name, scene);
             var torusKnot = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
             var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
@@ -1127,7 +1121,6 @@ var BABYLON;
         };
         };
 
 
         // Plane & ground
         // Plane & ground
-        //ANY
         Mesh.CreatePlane = function (name, size, scene, updatable) {
         Mesh.CreatePlane = function (name, size, scene, updatable) {
             var plane = new BABYLON.Mesh(name, scene);
             var plane = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreatePlane(size);
             var vertexData = BABYLON.VertexData.CreatePlane(size);
@@ -1137,7 +1130,6 @@ var BABYLON;
             return plane;
             return plane;
         };
         };
 
 
-        //ANY
         Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
         Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
             var ground = new BABYLON.Mesh(name, scene);
             var ground = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
             var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
@@ -1147,17 +1139,10 @@ var BABYLON;
             return ground;
             return ground;
         };
         };
 
 
-        //ANY
         Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
         Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
             var ground = new BABYLON.Mesh(name, scene);
             var ground = new BABYLON.Mesh(name, scene);
 
 
             var onload = function (img) {
             var onload = function (img) {
-                var indices = [];
-                var positions = [];
-                var normals = [];
-                var uvs = [];
-                var row, col;
-
                 // Getting height map data
                 // Getting height map data
                 var canvas = document.createElement("canvas");
                 var canvas = document.createElement("canvas");
                 var context = canvas.getContext("2d");
                 var context = canvas.getContext("2d");
@@ -1168,52 +1153,11 @@ var BABYLON;
 
 
                 context.drawImage(img, 0, 0);
                 context.drawImage(img, 0, 0);
 
 
+                // Create VertexData from map data
                 var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
                 var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
+                var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
 
 
-                for (row = 0; row <= subdivisions; row++) {
-                    for (col = 0; col <= subdivisions; col++) {
-                        var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
-
-                        // Compute height
-                        var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
-                        var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
-
-                        var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
-                        var r = buffer[pos] / 255.0;
-                        var g = buffer[pos + 1] / 255.0;
-                        var b = buffer[pos + 2] / 255.0;
-
-                        var gradient = r * 0.3 + g * 0.59 + b * 0.11;
-
-                        position.y = minHeight + (maxHeight - minHeight) * gradient;
-
-                        // Add  vertex
-                        positions.push(position.x, position.y, position.z);
-                        normals.push(0, 0, 0);
-                        uvs.push(col / subdivisions, 1.0 - row / subdivisions);
-                    }
-                }
-
-                for (row = 0; row < subdivisions; row++) {
-                    for (col = 0; col < subdivisions; col++) {
-                        indices.push(col + 1 + (row + 1) * (subdivisions + 1));
-                        indices.push(col + 1 + row * (subdivisions + 1));
-                        indices.push(col + row * (subdivisions + 1));
-
-                        indices.push(col + (row + 1) * (subdivisions + 1));
-                        indices.push(col + 1 + (row + 1) * (subdivisions + 1));
-                        indices.push(col + row * (subdivisions + 1));
-                    }
-                }
-
-                // Normals
-                BABYLON.VertexData.ComputeNormals(positions, indices, normals);
-
-                // Transfer
-                ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
-                ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
-                ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
-                ground.setIndices(indices);
+                vertexData.applyToMesh(ground, updatable);
 
 
                 ground._isReady = true;
                 ground._isReady = true;
             };
             };

+ 35 - 89
Babylon/Mesh/babylon.mesh.ts

@@ -12,7 +12,7 @@
         public rotation = new BABYLON.Vector3(0, 0, 0);
         public rotation = new BABYLON.Vector3(0, 0, 0);
         public rotationQuaternion = null;
         public rotationQuaternion = null;
         public scaling = new BABYLON.Vector3(1, 1, 1);
         public scaling = new BABYLON.Vector3(1, 1, 1);
-        public delayLoadState = 0; //ANY; BABYLON.Engine.DELAYLOADSTATE_NONE
+        public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE
         public material = null;
         public material = null;
         public isVisible = true;
         public isVisible = true;
         public isPickable = true;
         public isPickable = true;
@@ -26,7 +26,7 @@
         public renderingGroupId = 0;
         public renderingGroupId = 0;
         public infiniteDistance = false;
         public infiniteDistance = false;
         public showBoundingBox = false;
         public showBoundingBox = false;
-        public subMeshes; //ANY
+        public subMeshes: SubMesh[];
         public delayLoadingFile: string;
         public delayLoadingFile: string;
 
 
         // Cache
         // Cache
@@ -64,8 +64,7 @@
         private _indexBuffer;
         private _indexBuffer;
         private _delayLoadingFunction: (any, Mesh) => void;
         private _delayLoadingFunction: (any, Mesh) => void;
 
 
-        //ANY
-        constructor(name: string, scene) {
+        constructor(name: string, scene: Scene) {
             super(name, scene);
             super(name, scene);
 
 
             scene.meshes.push(this);
             scene.meshes.push(this);
@@ -360,7 +359,7 @@
                     zero = this.getScene().activeCamera.position;
                     zero = this.getScene().activeCamera.position;
                 } else {
                 } else {
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
-                        zero.x = localPosition.x + 0.001;//ANY:BABYLON.Engine.epsilon
+                        zero.x = localPosition.x + BABYLON.Engine.Epsilon;
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
                         zero.y = localPosition.y + 0.001;
                         zero.y = localPosition.y + 0.001;
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
                     if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
@@ -536,9 +535,8 @@
             effectiveMaterial.unbind();
             effectiveMaterial.unbind();
         }
         }
 
 
-        //ANY
-        public getEmittedParticleSystems() {
-            var results = [];
+        public getEmittedParticleSystems(): ParticleSystem[] {
+            var results = new Array<ParticleSystem>();
             for (var index = 0; index < this.getScene().particleSystems.length; index++) {
             for (var index = 0; index < this.getScene().particleSystems.length; index++) {
                 var particleSystem = this.getScene().particleSystems[index];
                 var particleSystem = this.getScene().particleSystems[index];
                 if (particleSystem.emitter === this) {
                 if (particleSystem.emitter === this) {
@@ -549,9 +547,8 @@
             return results;
             return results;
         }
         }
 
 
-        //ANY
-        public getHierarchyEmittedParticleSystems() {
-            var results = [];
+        public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
+            var results = new Array<ParticleSystem>();
             var descendants = this.getDescendants();
             var descendants = this.getDescendants();
             descendants.push(this);
             descendants.push(this);
 
 
@@ -578,19 +575,19 @@
         }
         }
 
 
         public isInFrustum(frustumPlanes: Plane[]): boolean {
         public isInFrustum(frustumPlanes: Plane[]): boolean {
-            if (this.delayLoadState === 2) { //ANY BABYLON.Engine.DELAYLOADSTATE_LOADING
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                 return false;
                 return false;
             }
             }
 
 
             var result = this._boundingInfo.isInFrustum(frustumPlanes);
             var result = this._boundingInfo.isInFrustum(frustumPlanes);
 
 
-            if (result && this.delayLoadState === 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED
-                this.delayLoadState = 2; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADING
+            if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { 
+                this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING; 
                 this.getScene()._addPendingData(this);
                 this.getScene()._addPendingData(this);
 
 
                 Tools.LoadFile(this.delayLoadingFile, data => {
                 Tools.LoadFile(this.delayLoadingFile, data => {
                     this._delayLoadingFunction(JSON.parse(data), this);
                     this._delayLoadingFunction(JSON.parse(data), this);
-                    this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED; 
                     this.getScene()._removePendingData(this);
                     this.getScene()._removePendingData(this);
                 }, () => { }, this.getScene().database);
                 }, () => { }, this.getScene().database);
             }
             }
@@ -781,7 +778,7 @@
 
 
             this._generatePointsArray();
             this._generatePointsArray();
 
 
-            var intersectInfo = null;
+            var intersectInfo: IntersectionInfo = null;
 
 
             for (var index = 0; index < this.subMeshes.length; index++) {
             for (var index = 0; index < this.subMeshes.length; index++) {
                 var subMesh = this.subMeshes[index];
                 var subMesh = this.subMeshes[index];
@@ -940,7 +937,9 @@
 
 
         // Physics
         // Physics
         public setPhysicsState(options): void {
         public setPhysicsState(options): void {
-            if (!this.getScene()._physicsEngine) {
+            var physicsEngine = this.getScene().getPhysicsEngine();
+
+            if (!physicsEngine) {
                 return;
                 return;
             }
             }
 
 
@@ -955,11 +954,11 @@
             this._physicRestitution = options.restitution;
             this._physicRestitution = options.restitution;
 
 
             if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
             if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
-                this.getScene()._physicsEngine._unregisterMesh(this);
+                physicsEngine._unregisterMesh(this);
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._registerMesh(this, options);
+            physicsEngine._registerMesh(this, options);
         }
         }
 
 
         public getPhysicsImpostor(): number {
         public getPhysicsImpostor(): number {
@@ -999,7 +998,7 @@
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._applyImpulse(this, force, contactPoint);
+            this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
         }
         }
 
 
         public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3): void {
         public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3): void {
@@ -1007,7 +1006,7 @@
                 return;
                 return;
             }
             }
 
 
-            this.getScene()._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
+            this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
         }
         }
 
 
         // Geometric tools
         // Geometric tools
@@ -1097,8 +1096,7 @@
         }
         }
 
 
         // Statics
         // Statics
-        //ANY
-        public static CreateBox(name: string, size: number, scene, updatable?: boolean): Mesh {
+        public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
             var box = new BABYLON.Mesh(name, scene);
             var box = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateBox(size);
             var vertexData = BABYLON.VertexData.CreateBox(size);
 
 
@@ -1106,8 +1104,8 @@
 
 
             return box;
             return box;
         }
         }
-        //ANY
-        public static CreateSphere(name: string, segments: number, diameter: number, scene, updatable?: boolean): Mesh {
+
+        public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
             var sphere = new BABYLON.Mesh(name, scene);
             var sphere = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
             var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
 
 
@@ -1117,8 +1115,7 @@
         }
         }
 
 
         // Cylinder and cone (Code inspired by SharpDX.org)
         // Cylinder and cone (Code inspired by SharpDX.org)
-        //ANY
-        public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene, updatable?: boolean): Mesh {
+        public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
             var cylinder = new BABYLON.Mesh(name, scene);
             var cylinder = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
             var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
 
 
@@ -1128,8 +1125,7 @@
         }
         }
 
 
         // Torus  (Code from SharpDX.org)
         // Torus  (Code from SharpDX.org)
-        //ANY
-        public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene, updatable?: boolean): Mesh {
+        public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
             var torus = new BABYLON.Mesh(name, scene);
             var torus = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
             var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
 
 
@@ -1137,8 +1133,8 @@
 
 
             return torus;
             return torus;
         }
         }
-        //ANY
-        public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene, updatable?: boolean): Mesh {
+
+        public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
             var torusKnot = new BABYLON.Mesh(name, scene);
             var torusKnot = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
             var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
 
 
@@ -1148,8 +1144,7 @@
         }
         }
 
 
         // Plane & ground
         // Plane & ground
-        //ANY
-        public static CreatePlane(name: string, size: number, scene, updatable?: boolean): Mesh {
+        public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
             var plane = new BABYLON.Mesh(name, scene);
             var plane = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreatePlane(size);
             var vertexData = BABYLON.VertexData.CreatePlane(size);
 
 
@@ -1157,8 +1152,8 @@
 
 
             return plane;
             return plane;
         }
         }
-        //ANY
-        public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene, updatable?: boolean): Mesh {
+
+        public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
             var ground = new BABYLON.Mesh(name, scene);
             var ground = new BABYLON.Mesh(name, scene);
             var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
             var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
 
 
@@ -1166,17 +1161,11 @@
 
 
             return ground;
             return ground;
         }
         }
-        //ANY
-        public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene, updatable?: boolean): Mesh {
+
+        public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): Mesh {
             var ground = new BABYLON.Mesh(name, scene);
             var ground = new BABYLON.Mesh(name, scene);
 
 
             var onload = img => {
             var onload = img => {
-                var indices = [];
-                var positions = [];
-                var normals = [];
-                var uvs = [];
-                var row, col;
-
                 // Getting height map data
                 // Getting height map data
                 var canvas = document.createElement("canvas");
                 var canvas = document.createElement("canvas");
                 var context = canvas.getContext("2d");
                 var context = canvas.getContext("2d");
@@ -1187,54 +1176,11 @@
 
 
                 context.drawImage(img, 0, 0);
                 context.drawImage(img, 0, 0);
 
 
+                // Create VertexData from map data
                 var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
                 var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
+                var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
 
 
-                // Vertices
-                for (row = 0; row <= subdivisions; row++) {
-                    for (col = 0; col <= subdivisions; col++) {
-                        var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
-
-                        // Compute height
-                        var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
-                        var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
-
-                        var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
-                        var r = buffer[pos] / 255.0;
-                        var g = buffer[pos + 1] / 255.0;
-                        var b = buffer[pos + 2] / 255.0;
-
-                        var gradient = r * 0.3 + g * 0.59 + b * 0.11;
-
-                        position.y = minHeight + (maxHeight - minHeight) * gradient;
-
-                        // Add  vertex
-                        positions.push(position.x, position.y, position.z);
-                        normals.push(0, 0, 0);
-                        uvs.push(col / subdivisions, 1.0 - row / subdivisions);
-                    }
-                }
-
-                // Indices
-                for (row = 0; row < subdivisions; row++) {
-                    for (col = 0; col < subdivisions; col++) {
-                        indices.push(col + 1 + (row + 1) * (subdivisions + 1));
-                        indices.push(col + 1 + row * (subdivisions + 1));
-                        indices.push(col + row * (subdivisions + 1));
-
-                        indices.push(col + (row + 1) * (subdivisions + 1));
-                        indices.push(col + 1 + (row + 1) * (subdivisions + 1));
-                        indices.push(col + row * (subdivisions + 1));
-                    }
-                }
-
-                // Normals
-                BABYLON.VertexData.ComputeNormals(positions, indices, normals);
-
-                // Transfer
-                ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
-                ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
-                ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
-                ground.setIndices(indices);
+                vertexData.applyToMesh(ground, updatable);
 
 
                 ground._isReady = true;
                 ground._isReady = true;
             };
             };

+ 57 - 0
Babylon/Mesh/babylon.mesh.vertexData.js

@@ -528,6 +528,63 @@
             return vertexData;
             return vertexData;
         };
         };
 
 
+        VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
+            var indices = [];
+            var positions = [];
+            var normals = [];
+            var uvs = [];
+            var row, col;
+
+            for (row = 0; row <= subdivisions; row++) {
+                for (col = 0; col <= subdivisions; col++) {
+                    var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
+
+                    // Compute height
+                    var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
+                    var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
+
+                    var pos = (heightMapX + heightMapY * bufferWidth) * 4;
+                    var r = buffer[pos] / 255.0;
+                    var g = buffer[pos + 1] / 255.0;
+                    var b = buffer[pos + 2] / 255.0;
+
+                    var gradient = r * 0.3 + g * 0.59 + b * 0.11;
+
+                    position.y = minHeight + (maxHeight - minHeight) * gradient;
+
+                    // Add  vertex
+                    positions.push(position.x, position.y, position.z);
+                    normals.push(0, 0, 0);
+                    uvs.push(col / subdivisions, 1.0 - row / subdivisions);
+                }
+            }
+
+            for (row = 0; row < subdivisions; row++) {
+                for (col = 0; col < subdivisions; col++) {
+                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
+                    indices.push(col + 1 + row * (subdivisions + 1));
+                    indices.push(col + row * (subdivisions + 1));
+
+                    indices.push(col + (row + 1) * (subdivisions + 1));
+                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
+                    indices.push(col + row * (subdivisions + 1));
+                }
+            }
+
+            // Normals
+            BABYLON.VertexData.ComputeNormals(positions, indices, normals);
+
+            // Result
+            var vertexData = new BABYLON.VertexData();
+
+            vertexData.indices = indices;
+            vertexData.positions = positions;
+            vertexData.normals = normals;
+            vertexData.uvs = uvs;
+
+            return vertexData;
+        };
+
         VertexData.CreatePlane = function (size) {
         VertexData.CreatePlane = function (size) {
             var indices = [];
             var indices = [];
             var positions = [];
             var positions = [];

+ 59 - 0
Babylon/Mesh/babylon.mesh.vertexData.ts

@@ -539,6 +539,65 @@
             return vertexData;
             return vertexData;
         }
         }
 
 
+        public static CreateGroundFromHeightMap(width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, buffer: Uint8Array, bufferWidth:  number, bufferHeight: number): VertexData {
+            var indices = [];
+            var positions = [];
+            var normals = [];
+            var uvs = [];
+            var row, col;
+
+            // Vertices
+            for (row = 0; row <= subdivisions; row++) {
+                for (col = 0; col <= subdivisions; col++) {
+                    var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
+
+                    // Compute height
+                    var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
+                    var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
+
+                    var pos = (heightMapX + heightMapY * bufferWidth) * 4;
+                    var r = buffer[pos] / 255.0;
+                    var g = buffer[pos + 1] / 255.0;
+                    var b = buffer[pos + 2] / 255.0;
+
+                    var gradient = r * 0.3 + g * 0.59 + b * 0.11;
+
+                    position.y = minHeight + (maxHeight - minHeight) * gradient;
+
+                    // Add  vertex
+                    positions.push(position.x, position.y, position.z);
+                    normals.push(0, 0, 0);
+                    uvs.push(col / subdivisions, 1.0 - row / subdivisions);
+                }
+            }
+
+            // Indices
+            for (row = 0; row < subdivisions; row++) {
+                for (col = 0; col < subdivisions; col++) {
+                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
+                    indices.push(col + 1 + row * (subdivisions + 1));
+                    indices.push(col + row * (subdivisions + 1));
+
+                    indices.push(col + (row + 1) * (subdivisions + 1));
+                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
+                    indices.push(col + row * (subdivisions + 1));
+                }
+            }
+
+            // Normals
+            BABYLON.VertexData.ComputeNormals(positions, indices, normals);
+
+            // Result
+            var vertexData = new BABYLON.VertexData();
+
+            vertexData.indices = indices;
+            vertexData.positions = positions;
+            vertexData.normals = normals;
+            vertexData.uvs = uvs;
+
+            return vertexData;
+        }
+
         public static CreatePlane(size: number): VertexData {
         public static CreatePlane(size: number): VertexData {
             var indices = [];
             var indices = [];
             var positions = [];
             var positions = [];

+ 0 - 3
Babylon/Mesh/babylon.subMesh.js

@@ -20,7 +20,6 @@
             return this._mesh;
             return this._mesh;
         };
         };
 
 
-        //ANY
         SubMesh.prototype.getMaterial = function () {
         SubMesh.prototype.getMaterial = function () {
             var rootMaterial = this._mesh.material;
             var rootMaterial = this._mesh.material;
 
 
@@ -63,7 +62,6 @@
             this._mesh.render(this);
             this._mesh.render(this);
         };
         };
 
 
-        //ANY
         SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
         SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
             if (!this._linesIndexBuffer) {
             if (!this._linesIndexBuffer) {
                 var linesIndices = [];
                 var linesIndices = [];
@@ -82,7 +80,6 @@
             return ray.intersectsBox(this._boundingInfo.boundingBox);
             return ray.intersectsBox(this._boundingInfo.boundingBox);
         };
         };
 
 
-        //ANY create intersectinfo class
         SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
         SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
             var intersectInfo = null;
             var intersectInfo = null;
 
 

+ 5 - 8
Babylon/Mesh/babylon.subMesh.ts

@@ -4,7 +4,7 @@
 
 
         private _mesh: Mesh;
         private _mesh: Mesh;
         private _boundingInfo: BoundingInfo;
         private _boundingInfo: BoundingInfo;
-        private _linesIndexBuffer; //ANY
+        private _linesIndexBuffer: WebGLBuffer;
         public _lastColliderWorldVertices: Vector3[];
         public _lastColliderWorldVertices: Vector3[];
         public _trianglePlanes: Plane[];
         public _trianglePlanes: Plane[];
         public _lastColliderTransformMatrix: Matrix;
         public _lastColliderTransformMatrix: Matrix;
@@ -24,8 +24,7 @@
             return this._mesh;
             return this._mesh;
         }
         }
 
 
-        //ANY
-        public getMaterial() {
+        public getMaterial(): Material {
             var rootMaterial = this._mesh.material;
             var rootMaterial = this._mesh.material;
 
 
             if (rootMaterial && rootMaterial.getSubMaterial) {
             if (rootMaterial && rootMaterial.getSubMaterial) {
@@ -67,8 +66,7 @@
             this._mesh.render(this);
             this._mesh.render(this);
         }
         }
 
 
-        //ANY
-        public getLinesIndexBuffer(indices: number[], engine) {
+        public getLinesIndexBuffer(indices: number[], engine): WebGLBuffer {
             if (!this._linesIndexBuffer) {
             if (!this._linesIndexBuffer) {
                 var linesIndices = [];
                 var linesIndices = [];
 
 
@@ -88,9 +86,8 @@
             return ray.intersectsBox(this._boundingInfo.boundingBox);
             return ray.intersectsBox(this._boundingInfo.boundingBox);
         }
         }
 
 
-        //ANY create intersectinfo class
-        public intersects(ray: Ray, positions: Vector3[], indices: number[], fastCheck?: boolean) {
-            var intersectInfo = null;
+        public intersects(ray: Ray, positions: Vector3[], indices: number[], fastCheck?: boolean): IntersectionInfo {
+            var intersectInfo: IntersectionInfo = null;
 
 
             // Triangles test
             // Triangles test
             for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
             for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {

+ 0 - 1
Babylon/Mesh/babylon.vertexBuffer.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var VertexBuffer = (function () {
     var VertexBuffer = (function () {
-        //ANY
         function VertexBuffer(mesh, data, kind, updatable, engine) {
         function VertexBuffer(mesh, data, kind, updatable, engine) {
             this._mesh = mesh;
             this._mesh = mesh;
             this._engine = engine || mesh.getScene().getEngine();
             this._engine = engine || mesh.getScene().getEngine();

+ 3 - 4
Babylon/Mesh/babylon.vertexBuffer.ts

@@ -1,15 +1,14 @@
 module BABYLON {
 module BABYLON {
     export class VertexBuffer {
     export class VertexBuffer {
-        private _mesh; //ANY
-        private _engine; //ANY
+        private _mesh: Mesh;
+        private _engine: Engine;
         private _buffer: WebGLBuffer;
         private _buffer: WebGLBuffer;
         private _data: number[];
         private _data: number[];
         private _updatable: boolean;
         private _updatable: boolean;
         private _kind: string;
         private _kind: string;
         private _strideSize: number;
         private _strideSize: number;
 
 
-        //ANY
-        constructor(mesh, data: number[], kind: string, updatable: boolean, engine?) {
+        constructor(mesh: Mesh, data: number[], kind: string, updatable: boolean, engine?: Engine) {
             this._mesh = mesh;
             this._mesh = mesh;
             this._engine = engine || mesh.getScene().getEngine();
             this._engine = engine || mesh.getScene().getEngine();
             this._updatable = updatable;
             this._updatable = updatable;

+ 19 - 18
Babylon/Particles/babylon.particle.js

@@ -1,18 +1,19 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.Particle = function () {
-        this.position = BABYLON.Vector3.Zero();
-        this.direction = BABYLON.Vector3.Zero();
-        this.color = new BABYLON.Color4(0, 0, 0, 0);
-        this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
-    };    
-
-    BABYLON.Particle.prototype.lifeTime = 1.0;
-    BABYLON.Particle.prototype.age = 0;
-    BABYLON.Particle.prototype.size = 0;
-    BABYLON.Particle.prototype.angle = 0;
-    BABYLON.Particle.prototype.angularSpeed = 0;
-})();
+var BABYLON;
+(function (BABYLON) {
+    var Particle = (function () {
+        function Particle() {
+            this.position = BABYLON.Vector3.Zero();
+            this.direction = BABYLON.Vector3.Zero();
+            this.color = new BABYLON.Color4(0, 0, 0, 0);
+            this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
+            this.lifeTime = 1.0;
+            this.age = 0;
+            this.size = 0;
+            this.angle = 0;
+            this.angularSpeed = 0;
+        }
+        return Particle;
+    })();
+    BABYLON.Particle = Particle;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.particle.js.map

+ 13 - 0
Babylon/Particles/babylon.particle.ts

@@ -0,0 +1,13 @@
+module BABYLON {
+    export class Particle {
+        public position = BABYLON.Vector3.Zero();
+        public direction = BABYLON.Vector3.Zero();
+        public color = new BABYLON.Color4(0, 0, 0, 0);
+        public colorStep = new BABYLON.Color4(0, 0, 0, 0);
+        public lifeTime = 1.0;
+        public age = 0;
+        public size = 0;
+        public angle = 0;
+        public angularSpeed = 0;
+    }
+} 

+ 313 - 329
Babylon/Particles/babylon.particleSystem.js

@@ -1,8 +1,5 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
+var BABYLON;
+(function (BABYLON) {
     var randomNumber = function (min, max) {
     var randomNumber = function (min, max) {
         if (min == max) {
         if (min == max) {
             return (min);
             return (min);
@@ -13,383 +10,370 @@ var BABYLON = BABYLON || {};
         return ((random * (max - min)) + min);
         return ((random * (max - min)) + min);
     };
     };
 
 
-    BABYLON.ParticleSystem = function (name, capacity, scene) {
-        this.name = name;
-        this.id = name;
-        this._capacity = capacity;
-
-        this._scene = scene;
-
-        scene.particleSystems.push(this);
-
-        // Vectors and colors
-        this.gravity = BABYLON.Vector3.Zero();
-        this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
-        this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
-        this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
-        this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
-        this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-        this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-        this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
-        this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-
-        // Particles
-        this.particles = [];
-        this._stockParticles = [];
-        this._newPartsExcess = 0;
-
-        // VBO
-        this._vertexDeclaration = [3, 4, 4];
-        this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
-        this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
-
-        var indices = [];
-        var index = 0;
-        for (var count = 0; count < capacity; count++) {
-            indices.push(index);
-            indices.push(index + 1);
-            indices.push(index + 2);
-            indices.push(index);
-            indices.push(index + 2);
-            indices.push(index + 3);
-            index += 4;
-        }
-
-        this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-
-        this._vertices = new Float32Array(capacity * this._vertexStrideSize);
-        
-        // Internals
-        this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
-        this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
-        this._scaledDirection = BABYLON.Vector3.Zero();
-        this._scaledGravity = BABYLON.Vector3.Zero();
-        this._currentRenderId = -1;
-    };
-
-    // Members
-    BABYLON.ParticleSystem.prototype.renderingGroupId = 0;
-    BABYLON.ParticleSystem.prototype.emitter = null;
-    BABYLON.ParticleSystem.prototype.emitRate = 10;
-    BABYLON.ParticleSystem.prototype.manualEmitCount = -1;
-    BABYLON.ParticleSystem.prototype.updateSpeed = 0.01;
-    BABYLON.ParticleSystem.prototype.targetStopDuration = 0;
-    BABYLON.ParticleSystem.prototype.disposeOnStop = false;
-
-    BABYLON.ParticleSystem.prototype.minEmitPower = 1;
-    BABYLON.ParticleSystem.prototype.maxEmitPower = 1;
-
-    BABYLON.ParticleSystem.prototype.minLifeTime = 1;
-    BABYLON.ParticleSystem.prototype.maxLifeTime = 1;
-
-    BABYLON.ParticleSystem.prototype.minSize = 1;
-    BABYLON.ParticleSystem.prototype.maxSize = 1;
-    BABYLON.ParticleSystem.prototype.minAngularSpeed = 0;
-    BABYLON.ParticleSystem.prototype.maxAngularSpeed = 0;
-
-    BABYLON.ParticleSystem.prototype.particleTexture = null;
-    
-    BABYLON.ParticleSystem.prototype.onDispose = null;
-
-    BABYLON.ParticleSystem.prototype.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
-
-    BABYLON.ParticleSystem.prototype.forceDepthWrite = false;
-
-    // Methods   
-    BABYLON.ParticleSystem.prototype.isAlive = function () {
-        return this._alive;
-    };
-
-    BABYLON.ParticleSystem.prototype.start = function () {
-        this._started = true;
-        this._stopped = false;
-        this._actualFrame = 0;
-    };
-
-    BABYLON.ParticleSystem.prototype.stop = function () {
-        this._stopped = true;
-    };
-    
-    BABYLON.ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
-        var offset = index * 11;
-        this._vertices[offset] = particle.position.x;
-        this._vertices[offset + 1] = particle.position.y;
-        this._vertices[offset + 2] = particle.position.z;
-        this._vertices[offset + 3] = particle.color.r;
-        this._vertices[offset + 4] = particle.color.g;
-        this._vertices[offset + 5] = particle.color.b;
-        this._vertices[offset + 6] = particle.color.a;
-        this._vertices[offset + 7] = particle.angle;
-        this._vertices[offset + 8] = particle.size;
-        this._vertices[offset + 9] = offsetX;
-        this._vertices[offset + 10] = offsetY;
-    };
-    
-    BABYLON.ParticleSystem.prototype._update = function (newParticles) {
-        // Update current
-        this._alive = this.particles.length > 0;
-        for (var index = 0; index < this.particles.length; index++) {
-            var particle = this.particles[index];
-            particle.age += this._scaledUpdateSpeed;
-
-            if (particle.age >= particle.lifeTime) {
-                this._stockParticles.push(this.particles.splice(index, 1)[0]);
-                index--;
-                continue;
+    var ParticleSystem = (function () {
+        function ParticleSystem(name, capacity, scene) {
+            this.name = name;
+            this.renderingGroupId = 0;
+            this.emitter = null;
+            this.emitRate = 10;
+            this.manualEmitCount = -1;
+            this.updateSpeed = 0.01;
+            this.targetStopDuration = 0;
+            this.disposeOnStop = false;
+            this.minEmitPower = 1;
+            this.maxEmitPower = 1;
+            this.minLifeTime = 1;
+            this.maxLifeTime = 1;
+            this.minSize = 1;
+            this.maxSize = 1;
+            this.minAngularSpeed = 0;
+            this.maxAngularSpeed = 0;
+            this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
+            this.forceDepthWrite = false;
+            this.gravity = BABYLON.Vector3.Zero();
+            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
+            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
+            this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
+            this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
+            this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
+            this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.particles = new Array();
+            this._vertexDeclaration = [3, 4, 4];
+            this._vertexStrideSize = 11 * 4;
+            this._stockParticles = new Array();
+            this._newPartsExcess = 0;
+            this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
+            this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
+            this._scaledDirection = BABYLON.Vector3.Zero();
+            this._scaledGravity = BABYLON.Vector3.Zero();
+            this._currentRenderId = -1;
+            this._started = true;
+            this._stopped = false;
+            this._actualFrame = 0;
+            this.id = name;
+            this._capacity = capacity;
+
+            this._scene = scene;
+
+            scene.particleSystems.push(this);
+
+            // VBO
+            this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
+
+            var indices = [];
+            var index = 0;
+            for (var count = 0; count < capacity; count++) {
+                indices.push(index);
+                indices.push(index + 1);
+                indices.push(index + 2);
+                indices.push(index);
+                indices.push(index + 2);
+                indices.push(index + 3);
+                index += 4;
             }
             }
-            else {
-                particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
-                particle.color.addInPlace(this._scaledColorStep);
-
-                if (particle.color.a < 0)
-                    particle.color.a = 0;
-
-                particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
-                particle.position.addInPlace(this._scaledDirection);
 
 
-                particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
 
 
-                this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
-                particle.direction.addInPlace(this._scaledGravity);
-            }
-        }
-        
-        // Add new ones
-        var worldMatrix;
-
-        if (this.emitter.position) {
-            worldMatrix = this.emitter.getWorldMatrix();
-        } else {
-            worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
+            this._vertices = new Float32Array(capacity * this._vertexStrideSize);
         }
         }
-
-        for (var index = 0; index < newParticles; index++) {
-            if (this.particles.length == this._capacity) {
-                break;
+        ParticleSystem.prototype.getCapacity = function () {
+            return this._capacity;
+        };
+
+        ParticleSystem.prototype.isAlive = function () {
+            return this._alive;
+        };
+
+        ParticleSystem.prototype.start = function () {
+            this._started = true;
+            this._stopped = false;
+            this._actualFrame = 0;
+        };
+
+        ParticleSystem.prototype.stop = function () {
+            this._stopped = true;
+        };
+
+        ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
+            var offset = index * 11;
+            this._vertices[offset] = particle.position.x;
+            this._vertices[offset + 1] = particle.position.y;
+            this._vertices[offset + 2] = particle.position.z;
+            this._vertices[offset + 3] = particle.color.r;
+            this._vertices[offset + 4] = particle.color.g;
+            this._vertices[offset + 5] = particle.color.b;
+            this._vertices[offset + 6] = particle.color.a;
+            this._vertices[offset + 7] = particle.angle;
+            this._vertices[offset + 8] = particle.size;
+            this._vertices[offset + 9] = offsetX;
+            this._vertices[offset + 10] = offsetY;
+        };
+
+        ParticleSystem.prototype._update = function (newParticles) {
+            // Update current
+            this._alive = this.particles.length > 0;
+            for (var index = 0; index < this.particles.length; index++) {
+                var particle = this.particles[index];
+                particle.age += this._scaledUpdateSpeed;
+
+                if (particle.age >= particle.lifeTime) {
+                    this._stockParticles.push(this.particles.splice(index, 1)[0]);
+                    index--;
+                    continue;
+                } else {
+                    particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
+                    particle.color.addInPlace(this._scaledColorStep);
+
+                    if (particle.color.a < 0)
+                        particle.color.a = 0;
+
+                    particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
+                    particle.position.addInPlace(this._scaledDirection);
+
+                    particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
+
+                    this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
+                    particle.direction.addInPlace(this._scaledGravity);
+                }
             }
             }
 
 
-            if (this._stockParticles.length !== 0) {
-                particle = this._stockParticles.pop();
-                particle.age = 0;
+            // Add new ones
+            var worldMatrix;
+
+            if (this.emitter.position) {
+                worldMatrix = this.emitter.getWorldMatrix();
             } else {
             } else {
-                particle = new BABYLON.Particle();
+                worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
             }
             }
-            this.particles.push(particle);
 
 
-            var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
-
-            var randX = randomNumber(this.direction1.x, this.direction2.x);
-            var randY = randomNumber(this.direction1.y, this.direction2.y);
-            var randZ = randomNumber(this.direction1.z, this.direction2.z);
+            for (index = 0; index < newParticles; index++) {
+                if (this.particles.length == this._capacity) {
+                    break;
+                }
 
 
-            BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, particle.direction);
+                if (this._stockParticles.length !== 0) {
+                    particle = this._stockParticles.pop();
+                    particle.age = 0;
+                } else {
+                    particle = new BABYLON.Particle();
+                }
+                this.particles.push(particle);
 
 
-            particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
+                var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
 
 
-            particle.size = randomNumber(this.minSize, this.maxSize);
-            particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
+                var randX = randomNumber(this.direction1.x, this.direction2.x);
+                var randY = randomNumber(this.direction1.y, this.direction2.y);
+                var randZ = randomNumber(this.direction1.z, this.direction2.z);
 
 
-            randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
-            randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
-            randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
+                BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, particle.direction);
 
 
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, particle.position);
+                particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
 
 
-            var step = randomNumber(0, 1.0);
+                particle.size = randomNumber(this.minSize, this.maxSize);
+                particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
 
 
-            BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
+                randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
+                randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
+                randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
 
 
-            this.colorDead.subtractToRef(particle.color, this._colorDiff);
-            this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
-        }
-    };
+                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, particle.position);
 
 
-    BABYLON.ParticleSystem.prototype._getEffect = function () {
-        var defines = [];
-        
-        if (this._scene.clipPlane) {
-            defines.push("#define CLIPPLANE");
-        }
-        
-        // Effect
-        var join = defines.join("\n");
-        if (this._cachedDefines != join) {
-            this._cachedDefines = join;
-            this._effect = this._scene.getEngine().createEffect("particles",
-                ["position", "color", "options"],
-                ["invView", "view", "projection", "vClipPlane", "textureMask"],
-                ["diffuseSampler"], join);
-        }
+                var step = randomNumber(0, 1.0);
 
 
-        return this._effect;
-    };
+                BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
 
 
-    BABYLON.ParticleSystem.prototype.animate = function () {
-        if (!this._started)
-            return;
+                this.colorDead.subtractToRef(particle.color, this._colorDiff);
+                this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
+            }
+        };
 
 
-        var effect = this._getEffect();
+        ParticleSystem.prototype._getEffect = function () {
+            var defines = [];
 
 
-        // Check
-        if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
-            return;
-        
-        if (this._currentRenderId === this._scene.getRenderId()) {
-            return;
-        }
+            if (this._scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
+            }
 
 
-        this._currentRenderId = this._scene.getRenderId();
+            // Effect
+            var join = defines.join("\n");
+            if (this._cachedDefines != join) {
+                this._cachedDefines = join;
+                this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
+            }
 
 
-        this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
+            return this._effect;
+        };
 
 
-        // determine the number of particles we need to create   
-        var emitCout;
-        
-        if (this.manualEmitCount > -1) {
-            emitCout = this.manualEmitCount;
-            this.manualEmitCount = 0;
-        } else {
-            emitCout = this.emitRate;
-        }
+        ParticleSystem.prototype.animate = function () {
+            if (!this._started)
+                return;
 
 
-        var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
-        this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
+            var effect = this._getEffect();
 
 
-        if (this._newPartsExcess > 1.0) {
-            newParticles += this._newPartsExcess >> 0;
-            this._newPartsExcess -= this._newPartsExcess >> 0;
-        }
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
+                return;
 
 
-        this._alive = false;
+            if (this._currentRenderId === this._scene.getRenderId()) {
+                return;
+            }
 
 
-        if (!this._stopped) {
-            this._actualFrame += this._scaledUpdateSpeed;
+            this._currentRenderId = this._scene.getRenderId();
 
 
-            if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
-                this.stop();
-        } else {
-            newParticles = 0;
-        }
+            this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
 
 
-        this._update(newParticles);
+            // determine the number of particles we need to create
+            var emitCout;
 
 
-        // Stopped?
-        if (this._stopped) {
-            if (!this._alive) {
-                this._started = false;
-                if (this.disposeOnStop) {
-                    this._scene._toBeDisposed.push(this);
-                }
+            if (this.manualEmitCount > -1) {
+                emitCout = this.manualEmitCount;
+                this.manualEmitCount = 0;
+            } else {
+                emitCout = this.emitRate;
             }
             }
-        }
 
 
-        // Update VBO
-        var offset = 0;
-        for (var index = 0; index < this.particles.length; index++) {
-            var particle = this.particles[index];
+            var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
+            this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
 
 
-            this._appendParticleVertex(offset++, particle, 0, 0);
-            this._appendParticleVertex(offset++, particle, 1, 0);
-            this._appendParticleVertex(offset++, particle, 1, 1);
-            this._appendParticleVertex(offset++, particle, 0, 1);
-        }
-        var engine = this._scene.getEngine();
-        engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
-    };
+            if (this._newPartsExcess > 1.0) {
+                newParticles += this._newPartsExcess >> 0;
+                this._newPartsExcess -= this._newPartsExcess >> 0;
+            }
 
 
-    BABYLON.ParticleSystem.prototype.render = function () {
-        var effect = this._getEffect();
+            this._alive = false;
 
 
-        // Check
-        if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
-            return 0;
+            if (!this._stopped) {
+                this._actualFrame += this._scaledUpdateSpeed;
 
 
-        var engine = this._scene.getEngine();
+                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
+                    this.stop();
+            } else {
+                newParticles = 0;
+            }
 
 
-        // Render
-        engine.enableEffect(effect);
+            this._update(newParticles);
 
 
-        var viewMatrix = this._scene.getViewMatrix();
-        effect.setTexture("diffuseSampler", this.particleTexture);
-        effect.setMatrix("view", viewMatrix);
-        effect.setMatrix("projection", this._scene.getProjectionMatrix());
-        effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
+            // Stopped?
+            if (this._stopped) {
+                if (!this._alive) {
+                    this._started = false;
+                    if (this.disposeOnStop) {
+                        this._scene._toBeDisposed.push(this);
+                    }
+                }
+            }
 
 
-        if (this._scene.clipPlane) {
-            var clipPlane = this._scene.clipPlane;
-            var invView = viewMatrix.clone();
-            invView.invert();
-            effect.setMatrix("invView", invView);
-            effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
-        }        
+            // Update VBO
+            var offset = 0;
+            for (var index = 0; index < this.particles.length; index++) {
+                var particle = this.particles[index];
 
 
-        // VBOs
-        engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+                this._appendParticleVertex(offset++, particle, 0, 0);
+                this._appendParticleVertex(offset++, particle, 1, 0);
+                this._appendParticleVertex(offset++, particle, 1, 1);
+                this._appendParticleVertex(offset++, particle, 0, 1);
+            }
+            var engine = this._scene.getEngine();
+            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
+        };
+
+        ParticleSystem.prototype.render = function () {
+            var effect = this._getEffect();
+
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
+                return 0;
+
+            var engine = this._scene.getEngine();
+
+            // Render
+            engine.enableEffect(effect);
+
+            var viewMatrix = this._scene.getViewMatrix();
+            effect.setTexture("diffuseSampler", this.particleTexture);
+            effect.setMatrix("view", viewMatrix);
+            effect.setMatrix("projection", this._scene.getProjectionMatrix());
+            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
+
+            if (this._scene.clipPlane) {
+                var clipPlane = this._scene.clipPlane;
+                var invView = viewMatrix.clone();
+                invView.invert();
+                effect.setMatrix("invView", invView);
+                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
 
 
-        // Draw order
-        if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
-        } else {
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-        }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
 
 
-        if (this.forceDepthWrite) {
-            this.setDepthWrite(true);
-        }
+            // Draw order
+            if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
+            } else {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+            }
 
 
-        engine.draw(true, 0, this.particles.length * 6);
-        engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            if (this.forceDepthWrite) {
+                engine.setDepthWrite(true);
+            }
 
 
-        return this.particles.length;
-    };
+            engine.draw(true, 0, this.particles.length * 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
 
 
-    BABYLON.ParticleSystem.prototype.dispose = function () {
-        if (this._vertexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-            this._vertexBuffer = null;
-        }
+            return this.particles.length;
+        };
 
 
-        if (this._indexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-            this._indexBuffer = null;
-        }
+        ParticleSystem.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
 
 
-        if (this.particleTexture) {
-            this.particleTexture.dispose();
-            this.particleTexture = null;
-        }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
 
 
-        // Remove from scene
-        var index = this._scene.particleSystems.indexOf(this);
-        this._scene.particleSystems.splice(index, 1);
-        
-        // Callback
-        if (this.onDispose) {
-            this.onDispose();
-        }
-    };
+            if (this.particleTexture) {
+                this.particleTexture.dispose();
+                this.particleTexture = null;
+            }
 
 
-    // Clone
-    BABYLON.ParticleSystem.prototype.clone = function(name, newEmitter) {
-        var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
+            // Remove from scene
+            var index = this._scene.particleSystems.indexOf(this);
+            this._scene.particleSystems.splice(index, 1);
 
 
-        BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
 
 
-        if (newEmitter === undefined) {
-            newEmitter = this.emitter;
-        }
+        // Clone
+        ParticleSystem.prototype.clone = function (name, newEmitter) {
+            var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
 
 
-        result.emitter = newEmitter;
-        if (this.particleTexture) {
-            result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
-        }
+            BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
 
 
-        result.start();
+            if (newEmitter === undefined) {
+                newEmitter = this.emitter;
+            }
 
 
-        return result;
-    };
-    
-    // Statics
-    BABYLON.ParticleSystem.BLENDMODE_ONEONE = 0;
-    BABYLON.ParticleSystem.BLENDMODE_STANDARD = 1;
-})();
+            result.emitter = newEmitter;
+            if (this.particleTexture) {
+                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
+            }
+
+            result.start();
+
+            return result;
+        };
+        ParticleSystem.BLENDMODE_ONEONE = 0;
+        ParticleSystem.BLENDMODE_STANDARD = 1;
+        return ParticleSystem;
+    })();
+    BABYLON.ParticleSystem = ParticleSystem;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.particleSystem.js.map

+ 406 - 0
Babylon/Particles/babylon.particleSystem.ts

@@ -0,0 +1,406 @@
+module BABYLON {
+    var randomNumber = (min: number, max: number): number => {
+        if (min == max) {
+            return (min);
+        }
+
+        var random = Math.random();
+
+        return ((random * (max - min)) + min);
+    }
+
+    export class ParticleSystem {
+        // Statics
+        public static BLENDMODE_ONEONE = 0;
+        public static BLENDMODE_STANDARD = 1;
+
+        // Members
+        public id: string;
+        public renderingGroupId = 0;
+        public emitter = null;
+        public emitRate = 10;
+        public manualEmitCount = -1;
+        public updateSpeed = 0.01;
+        public targetStopDuration = 0;
+        public disposeOnStop = false;
+
+        public minEmitPower = 1;
+        public maxEmitPower = 1;
+
+        public minLifeTime = 1;
+        public maxLifeTime = 1;
+
+        public minSize = 1;
+        public maxSize = 1;
+        public minAngularSpeed = 0;
+        public maxAngularSpeed = 0;
+
+        public particleTexture: Texture;
+
+        public onDispose: () => void;
+
+        public blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
+
+        public forceDepthWrite = false;
+
+        public gravity = BABYLON.Vector3.Zero();
+        public direction1 = new BABYLON.Vector3(0, 1.0, 0);
+        public direction2 = new BABYLON.Vector3(0, 1.0, 0);
+        public minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
+        public maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
+        public color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+        public color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+        public colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
+        public textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+        private particles = new Array<Particle>();
+
+        private _capacity: number;
+        private _scene: Scene;
+        private _vertexDeclaration = [3, 4, 4];
+        private _vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
+        private _stockParticles = new Array<Particle>();
+        private _newPartsExcess = 0;
+        private _vertexBuffer: WebGLBuffer;
+        private _indexBuffer: WebGLBuffer;
+        private _vertices: Float32Array;
+        private _effect: Effect;
+        private _cachedDefines: string;
+
+        private _scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
+        private _colorDiff = new BABYLON.Color4(0, 0, 0, 0);
+        private _scaledDirection = BABYLON.Vector3.Zero();
+        private _scaledGravity = BABYLON.Vector3.Zero();
+        private _currentRenderId = -1;
+
+        private _alive: boolean;
+        private _started = true;
+        private _stopped = false;
+        private _actualFrame = 0;
+        private _scaledUpdateSpeed: number;
+
+        constructor(public name: string, capacity: number, scene: Scene) {
+            this.id = name;
+            this._capacity = capacity;
+
+            this._scene = scene;
+
+            scene.particleSystems.push(this);
+
+            // VBO
+            this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
+
+            var indices = [];
+            var index = 0;
+            for (var count = 0; count < capacity; count++) {
+                indices.push(index);
+                indices.push(index + 1);
+                indices.push(index + 2);
+                indices.push(index);
+                indices.push(index + 2);
+                indices.push(index + 3);
+                index += 4;
+            }
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            this._vertices = new Float32Array(capacity * this._vertexStrideSize);
+        }
+
+        public getCapacity(): number {
+            return this._capacity;
+        }
+
+        public isAlive(): boolean {
+            return this._alive;
+        }
+
+        public start(): void {
+            this._started = true;
+            this._stopped = false;
+            this._actualFrame = 0;
+        }
+
+        public stop(): void {
+            this._stopped = true;
+        }
+
+        public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
+            var offset = index * 11;
+            this._vertices[offset] = particle.position.x;
+            this._vertices[offset + 1] = particle.position.y;
+            this._vertices[offset + 2] = particle.position.z;
+            this._vertices[offset + 3] = particle.color.r;
+            this._vertices[offset + 4] = particle.color.g;
+            this._vertices[offset + 5] = particle.color.b;
+            this._vertices[offset + 6] = particle.color.a;
+            this._vertices[offset + 7] = particle.angle;
+            this._vertices[offset + 8] = particle.size;
+            this._vertices[offset + 9] = offsetX;
+            this._vertices[offset + 10] = offsetY;
+        }
+
+        private _update(newParticles: number): void {
+            // Update current
+            this._alive = this.particles.length > 0;
+            for (var index = 0; index < this.particles.length; index++) {
+                var particle = this.particles[index];
+                particle.age += this._scaledUpdateSpeed;
+
+                if (particle.age >= particle.lifeTime) {
+                    this._stockParticles.push(this.particles.splice(index, 1)[0]);
+                    index--;
+                    continue;
+                }
+                else {
+                    particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
+                    particle.color.addInPlace(this._scaledColorStep);
+
+                    if (particle.color.a < 0)
+                        particle.color.a = 0;
+
+                    particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
+                    particle.position.addInPlace(this._scaledDirection);
+
+                    particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
+
+                    this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
+                    particle.direction.addInPlace(this._scaledGravity);
+                }
+            }
+
+            // Add new ones
+            var worldMatrix;
+
+            if (this.emitter.position) {
+                worldMatrix = this.emitter.getWorldMatrix();
+            } else {
+                worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
+            }
+
+            for (index = 0; index < newParticles; index++) {
+                if (this.particles.length == this._capacity) {
+                    break;
+                }
+
+                if (this._stockParticles.length !== 0) {
+                    particle = this._stockParticles.pop();
+                    particle.age = 0;
+                } else {
+                    particle = new BABYLON.Particle();
+                }
+                this.particles.push(particle);
+
+                var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
+
+                var randX = randomNumber(this.direction1.x, this.direction2.x);
+                var randY = randomNumber(this.direction1.y, this.direction2.y);
+                var randZ = randomNumber(this.direction1.z, this.direction2.z);
+
+                BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, particle.direction);
+
+                particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
+
+                particle.size = randomNumber(this.minSize, this.maxSize);
+                particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
+
+                randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
+                randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
+                randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
+
+                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, particle.position);
+
+                var step = randomNumber(0, 1.0);
+
+                BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
+
+                this.colorDead.subtractToRef(particle.color, this._colorDiff);
+                this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
+            }
+        }
+
+        private _getEffect(): Effect {
+            var defines = [];
+
+            if (this._scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
+            }
+
+            // Effect
+            var join = defines.join("\n");
+            if (this._cachedDefines != join) {
+                this._cachedDefines = join;
+                this._effect = this._scene.getEngine().createEffect("particles",
+                    ["position", "color", "options"],
+                    ["invView", "view", "projection", "vClipPlane", "textureMask"],
+                    ["diffuseSampler"], join);
+            }
+
+            return this._effect;
+        }
+
+        public animate(): void {
+            if (!this._started)
+                return;
+
+            var effect = this._getEffect();
+
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
+                return;
+
+            if (this._currentRenderId === this._scene.getRenderId()) {
+                return;
+            }
+
+            this._currentRenderId = this._scene.getRenderId();
+
+            this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
+
+            // determine the number of particles we need to create   
+            var emitCout;
+
+            if (this.manualEmitCount > -1) {
+                emitCout = this.manualEmitCount;
+                this.manualEmitCount = 0;
+            } else {
+                emitCout = this.emitRate;
+            }
+
+            var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
+            this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
+
+            if (this._newPartsExcess > 1.0) {
+                newParticles += this._newPartsExcess >> 0;
+                this._newPartsExcess -= this._newPartsExcess >> 0;
+            }
+
+            this._alive = false;
+
+            if (!this._stopped) {
+                this._actualFrame += this._scaledUpdateSpeed;
+
+                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
+                    this.stop();
+            } else {
+                newParticles = 0;
+            }
+
+            this._update(newParticles);
+
+            // Stopped?
+            if (this._stopped) {
+                if (!this._alive) {
+                    this._started = false;
+                    if (this.disposeOnStop) {
+                        this._scene._toBeDisposed.push(this);
+                    }
+                }
+            }
+
+            // Update VBO
+            var offset = 0;
+            for (var index = 0; index < this.particles.length; index++) {
+                var particle = this.particles[index];
+
+                this._appendParticleVertex(offset++, particle, 0, 0);
+                this._appendParticleVertex(offset++, particle, 1, 0);
+                this._appendParticleVertex(offset++, particle, 1, 1);
+                this._appendParticleVertex(offset++, particle, 0, 1);
+            }
+            var engine = this._scene.getEngine();
+            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
+        }
+
+        public render(): number {
+            var effect = this._getEffect();
+
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
+                return 0;
+
+            var engine = this._scene.getEngine();
+
+            // Render
+            engine.enableEffect(effect);
+
+            var viewMatrix = this._scene.getViewMatrix();
+            effect.setTexture("diffuseSampler", this.particleTexture);
+            effect.setMatrix("view", viewMatrix);
+            effect.setMatrix("projection", this._scene.getProjectionMatrix());
+            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
+
+            if (this._scene.clipPlane) {
+                var clipPlane = this._scene.clipPlane;
+                var invView = viewMatrix.clone();
+                invView.invert();
+                effect.setMatrix("invView", invView);
+                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+
+            // Draw order
+            if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
+            } else {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+            }
+
+            if (this.forceDepthWrite) {
+                engine.setDepthWrite(true);
+            }
+
+            engine.draw(true, 0, this.particles.length * 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+
+            return this.particles.length;
+        }
+
+        public dispose(): void {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+
+            if (this.particleTexture) {
+                this.particleTexture.dispose();
+                this.particleTexture = null;
+            }
+
+            // Remove from scene
+            var index = this._scene.particleSystems.indexOf(this);
+            this._scene.particleSystems.splice(index, 1);
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+
+        // Clone
+        public clone(name: string, newEmitter: any): ParticleSystem {
+            var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
+
+            BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
+
+            if (newEmitter === undefined) {
+                newEmitter = this.emitter;
+            }
+
+            result.emitter = newEmitter;
+            if (this.particleTexture) {
+                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
+            }
+
+            result.start();
+
+            return result;
+        }
+    }
+}  

+ 0 - 1
Babylon/PostProcess/babylon.anaglyphPostProcess.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var AnaglyphPostProcess = (function (_super) {
     var AnaglyphPostProcess = (function (_super) {
         __extends(AnaglyphPostProcess, _super);
         __extends(AnaglyphPostProcess, _super);
-        //ANY
         function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
         function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
             _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
             _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
         }
         }

+ 1 - 2
Babylon/PostProcess/babylon.anaglyphPostProcess.ts

@@ -1,7 +1,6 @@
 module BABYLON {
 module BABYLON {
     export class AnaglyphPostProcess extends PostProcess {
     export class AnaglyphPostProcess extends PostProcess {
-        //ANY
-        constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?, reusable?: boolean) {
+        constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean) {
             super(name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
             super(name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
         }
         }
     }
     }

+ 0 - 1
Babylon/PostProcess/babylon.passPostProcess.js

@@ -8,7 +8,6 @@ var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var PassPostProcess = (function (_super) {
     var PassPostProcess = (function (_super) {
         __extends(PassPostProcess, _super);
         __extends(PassPostProcess, _super);
-        //ANY
         function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
         function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
             _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
             _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
         }
         }

+ 1 - 2
Babylon/PostProcess/babylon.passPostProcess.ts

@@ -1,7 +1,6 @@
 module BABYLON {
 module BABYLON {
     export class PassPostProcess extends PostProcess {
     export class PassPostProcess extends PostProcess {
-        //ANY
-        constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?, reusable?: boolean) {
+        constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean) {
             super(name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
             super(name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
         }
         }
     }
     }

+ 8 - 6
Babylon/PostProcess/babylon.postProcess.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var PostProcess = (function () {
     var PostProcess = (function () {
-        //ANY
         function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
         function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
             this.name = name;
             this.name = name;
             this.onApply = null;
             this.onApply = null;
@@ -23,7 +22,7 @@
             }
             }
 
 
             this._renderRatio = ratio;
             this._renderRatio = ratio;
-            this.renderTargetSamplingMode = samplingMode ? samplingMode : 1; //ANY BABYLON.Texture.NEAREST_SAMPLINGMODE;
+            this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
             this._reusable = reusable || false;
             this._reusable = reusable || false;
 
 
             samplers = samplers || [];
             samplers = samplers || [];
@@ -31,13 +30,16 @@
 
 
             this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
             this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
         }
         }
-        // Methods
+        PostProcess.prototype.isReusable = function () {
+            return this._reusable;
+        };
+
         PostProcess.prototype.activate = function (camera) {
         PostProcess.prototype.activate = function (camera) {
             camera = camera || this._camera;
             camera = camera || this._camera;
 
 
             var scene = camera.getScene();
             var scene = camera.getScene();
-            var desiredWidth = this._engine._renderingCanvas.width * this._renderRatio;
-            var desiredHeight = this._engine._renderingCanvas.height * this._renderRatio;
+            var desiredWidth = this._engine.getRenderWidth() * this._renderRatio;
+            var desiredHeight = this._engine.getRenderHeight() * this._renderRatio;
             if (this.width !== desiredWidth || this.height !== desiredHeight) {
             if (this.width !== desiredWidth || this.height !== desiredHeight) {
                 if (this._textures.length > 0) {
                 if (this._textures.length > 0) {
                     for (var i = 0; i < this._textures.length; i++) {
                     for (var i = 0; i < this._textures.length; i++) {
@@ -80,7 +82,7 @@
             // States
             // States
             this._engine.enableEffect(this._effect);
             this._engine.enableEffect(this._effect);
             this._engine.setState(false);
             this._engine.setState(false);
-            this._engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+            this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
             this._engine.setDepthBuffer(false);
             this._engine.setDepthBuffer(false);
             this._engine.setDepthWrite(false);
             this._engine.setDepthWrite(false);
 
 

+ 10 - 9
Babylon/PostProcess/babylon.postProcess.ts

@@ -9,16 +9,15 @@
 
 
         private _onDispose = null;
         private _onDispose = null;
         private _camera: Camera;
         private _camera: Camera;
-        private _scene; //ANY
-        private _engine; //ANY
+        private _scene: Scene;
+        private _engine: Engine;
         private _renderRatio: number;
         private _renderRatio: number;
         private _reusable = false;
         private _reusable = false;
         public _textures = new BABYLON.SmartArray(2);
         public _textures = new BABYLON.SmartArray(2);
         public _currentRenderTextureInd = 0;
         public _currentRenderTextureInd = 0;
         private _effect: Effect;
         private _effect: Effect;
 
 
-        //ANY
-        constructor(public name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number, camera: Camera, samplingMode: number, engine, reusable?: boolean) {
+        constructor(public name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number, camera: Camera, samplingMode: number, engine?: Engine, reusable?: boolean) {
             if (camera != null) {
             if (camera != null) {
                 this._camera = camera;
                 this._camera = camera;
                 this._scene = camera.getScene();
                 this._scene = camera.getScene();
@@ -30,7 +29,7 @@
             }
             }
 
 
             this._renderRatio = ratio;
             this._renderRatio = ratio;
-            this.renderTargetSamplingMode = samplingMode ? samplingMode : 1; //ANY BABYLON.Texture.NEAREST_SAMPLINGMODE;
+            this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
             this._reusable = reusable || false;
             this._reusable = reusable || false;
 
 
             samplers = samplers || [];
             samplers = samplers || [];
@@ -42,14 +41,16 @@
                 samplers, "");
                 samplers, "");
         }
         }
 
 
-        // Methods
+        public isReusable(): boolean {
+            return this._reusable;
+        }
 
 
         public activate(camera: Camera): void {
         public activate(camera: Camera): void {
             camera = camera || this._camera;
             camera = camera || this._camera;
 
 
             var scene = camera.getScene();
             var scene = camera.getScene();
-            var desiredWidth = this._engine._renderingCanvas.width * this._renderRatio;
-            var desiredHeight = this._engine._renderingCanvas.height * this._renderRatio;
+            var desiredWidth = this._engine.getRenderWidth() * this._renderRatio;
+            var desiredHeight = this._engine.getRenderHeight() * this._renderRatio;
             if (this.width !== desiredWidth || this.height !== desiredHeight) {
             if (this.width !== desiredWidth || this.height !== desiredHeight) {
                 if (this._textures.length > 0) {
                 if (this._textures.length > 0) {
                     for (var i = 0; i < this._textures.length; i++) {
                     for (var i = 0; i < this._textures.length; i++) {
@@ -93,7 +94,7 @@
             // States
             // States
             this._engine.enableEffect(this._effect);
             this._engine.enableEffect(this._effect);
             this._engine.setState(false);
             this._engine.setState(false);
-            this._engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+            this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
             this._engine.setDepthBuffer(false);
             this._engine.setDepthBuffer(false);
             this._engine.setDepthWrite(false);
             this._engine.setDepthWrite(false);
 
 

+ 2 - 3
Babylon/Rendering/babylon.renderingGroup.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var RenderingGroup = (function () {
     var RenderingGroup = (function () {
-        //ANY
         function RenderingGroup(index, scene) {
         function RenderingGroup(index, scene) {
             this.index = index;
             this.index = index;
             this._opaqueSubMeshes = new BABYLON.SmartArray(256);
             this._opaqueSubMeshes = new BABYLON.SmartArray(256);
@@ -65,14 +64,14 @@
                 });
                 });
 
 
                 // Rendering
                 // Rendering
-                engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                 for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                 for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                     submesh = sortedArray[subIndex];
                     submesh = sortedArray[subIndex];
                     this._activeVertices += submesh.verticesCount;
                     this._activeVertices += submesh.verticesCount;
 
 
                     submesh.render();
                     submesh.render();
                 }
                 }
-                engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
             }
             }
             return true;
             return true;
         };
         };

+ 4 - 5
Babylon/Rendering/babylon.renderingGroup.ts

@@ -1,13 +1,12 @@
 module BABYLON {
 module BABYLON {
     export class RenderingGroup {
     export class RenderingGroup {
-        private _scene; //ANY
+        private _scene: Scene
         private _opaqueSubMeshes = new BABYLON.SmartArray(256);
         private _opaqueSubMeshes = new BABYLON.SmartArray(256);
         private _transparentSubMeshes = new BABYLON.SmartArray(256);
         private _transparentSubMeshes = new BABYLON.SmartArray(256);
         private _alphaTestSubMeshes = new BABYLON.SmartArray(256);
         private _alphaTestSubMeshes = new BABYLON.SmartArray(256);
         private _activeVertices: number;
         private _activeVertices: number;
 
 
-        //ANY
-        constructor(public index: number, scene) {
+        constructor(public index: number, scene: Scene) {
             this._scene = scene;
             this._scene = scene;
         }
         }
 
 
@@ -68,14 +67,14 @@
                 });
                 });
 
 
                 // Rendering
                 // Rendering
-                engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                 for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                 for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                     submesh = sortedArray[subIndex];
                     submesh = sortedArray[subIndex];
                     this._activeVertices += submesh.verticesCount;
                     this._activeVertices += submesh.verticesCount;
 
 
                     submesh.render();
                     submesh.render();
                 }
                 }
-                engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
             }
             }
             return true;
             return true;
         }
         }

+ 0 - 1
Babylon/Rendering/babylon.renderingManager.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var RenderingManager = (function () {
     var RenderingManager = (function () {
-        //ANY
         function RenderingManager(scene) {
         function RenderingManager(scene) {
             this._renderingGroups = new Array();
             this._renderingGroups = new Array();
             this._scene = scene;
             this._scene = scene;

+ 2 - 3
Babylon/Rendering/babylon.renderingManager.ts

@@ -2,12 +2,11 @@
     export class RenderingManager {
     export class RenderingManager {
         public static MAX_RENDERINGGROUPS = 4;
         public static MAX_RENDERINGGROUPS = 4;
 
 
-        private _scene; //ANY
+        private _scene: Scene;
         private _renderingGroups = new Array<RenderingGroup>();
         private _renderingGroups = new Array<RenderingGroup>();
         private _depthBufferAlreadyCleaned: boolean;
         private _depthBufferAlreadyCleaned: boolean;
 
 
-        //ANY
-        constructor(scene) {
+        constructor(scene: Scene) {
             this._scene = scene;
             this._scene = scene;
         }
         }
 
 

+ 4 - 5
Babylon/Sprites/babylon.spriteManager.js

@@ -1,7 +1,6 @@
 var BABYLON;
 var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
     var SpriteManager = (function () {
     var SpriteManager = (function () {
-        //ANY
         function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
         function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
             this.name = name;
             this.name = name;
             this.cellSize = cellSize;
             this.cellSize = cellSize;
@@ -108,7 +107,7 @@
             // Render
             // Render
             var effect = this._effectBase;
             var effect = this._effectBase;
 
 
-            if (this._scene.fogMode !== 0) {
+            if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                 effect = this._effectFog;
                 effect = this._effectFog;
             }
             }
 
 
@@ -122,7 +121,7 @@
             effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
             effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
 
 
             // Fog
             // Fog
-            if (this._scene.fogMode !== 0) {
+            if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                 effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                 effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                 effect.setColor3("vFogColor", this._scene.fogColor);
                 effect.setColor3("vFogColor", this._scene.fogColor);
             }
             }
@@ -137,9 +136,9 @@
             engine.setColorWrite(true);
             engine.setColorWrite(true);
             effect.setBool("alphaTest", false);
             effect.setBool("alphaTest", false);
 
 
-            engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
             engine.draw(true, 0, max * 6);
             engine.draw(true, 0, max * 6);
-            engine.setAlphaMode(0); //BABYLON.Engine.ALPHA_DISABLE);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
         };
         };
 
 
         SpriteManager.prototype.dispose = function () {
         SpriteManager.prototype.dispose = function () {

+ 11 - 12
Babylon/Sprites/babylon.spriteManager.ts

@@ -5,21 +5,20 @@
         public onDispose: () => void;
         public onDispose: () => void;
 
 
         private _capacity: number;
         private _capacity: number;
-        private _spriteTexture; //ANY
+        private _spriteTexture: Texture;
         private _epsilon: number;
         private _epsilon: number;
 
 
-        private _scene; //ANY
+        private _scene: Scene;
 
 
         private _vertexDeclaration = [3, 4, 4, 4];
         private _vertexDeclaration = [3, 4, 4, 4];
         private _vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
         private _vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
-        private _vertexBuffer; //ANY
-        private _indexBuffer; //ANY
+        private _vertexBuffer: WebGLBuffer
+        private _indexBuffer: WebGLBuffer;
         private _vertices: Float32Array;
         private _vertices: Float32Array;
-        private _effectBase; //ANY
-        private _effectFog; //ANY
+        private _effectBase: Effect;
+        private _effectFog: Effect;
 
 
-        //ANY
-        constructor(public name: string, imgUrl: string, capacity: number, public cellSize: number, scene, epsilon?: number) {
+        constructor(public name: string, imgUrl: string, capacity: number, public cellSize: number, scene: Scene, epsilon?: number) {
             this._capacity = capacity;
             this._capacity = capacity;
             this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
             this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
             this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
             this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
@@ -125,7 +124,7 @@
             // Render
             // Render
             var effect = this._effectBase;
             var effect = this._effectBase;
 
 
-            if (this._scene.fogMode !== 0) { //ANY BABYLON.Scene.FOGMODE_NONE) {
+            if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                 effect = this._effectFog;
                 effect = this._effectFog;
             }
             }
 
 
@@ -139,7 +138,7 @@
             effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
             effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
 
 
             // Fog
             // Fog
-            if (this._scene.fogMode !== 0) { //ANY BABYLON.Scene.FOGMODE_NONE) {
+            if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                 effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                 effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                 effect.setColor3("vFogColor", this._scene.fogColor);
                 effect.setColor3("vFogColor", this._scene.fogColor);
             }
             }
@@ -154,9 +153,9 @@
             engine.setColorWrite(true);
             engine.setColorWrite(true);
             effect.setBool("alphaTest", false);
             effect.setBool("alphaTest", false);
 
 
-            engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
             engine.draw(true, 0, max * 6);
             engine.draw(true, 0, max * 6);
-            engine.setAlphaMode(0); //BABYLON.Engine.ALPHA_DISABLE);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
         }
         }
 
 
         public dispose(): void {
         public dispose(): void {

+ 55 - 50
Babylon/Tools/babylon.sceneSerializer.js

@@ -1,28 +1,26 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-
+var BABYLON;
+(function (BABYLON) {
     var serializeLight = function (light) {
     var serializeLight = function (light) {
         var serializationObject = {};
         var serializationObject = {};
         serializationObject.name = light.name;
         serializationObject.name = light.name;
         serializationObject.id = light.id;
         serializationObject.id = light.id;
-        serializationObject.tags = light._tags;
+        serializationObject.tags = BABYLON.Tags.GetTags(light);
 
 
         if (light instanceof BABYLON.PointLight) {
         if (light instanceof BABYLON.PointLight) {
             serializationObject.type = 0;
             serializationObject.type = 0;
             serializationObject.position = light.position.asArray();
             serializationObject.position = light.position.asArray();
         } else if (light instanceof BABYLON.DirectionalLight) {
         } else if (light instanceof BABYLON.DirectionalLight) {
             serializationObject.type = 1;
             serializationObject.type = 1;
-            serializationObject.position = light.position.asArray();
-            serializationObject.direction = light.position.asArray();
+            var directionalLight = light;
+            serializationObject.position = directionalLight.position.asArray();
+            serializationObject.direction = directionalLight.direction.asArray();
         } else if (light instanceof BABYLON.SpotLight) {
         } else if (light instanceof BABYLON.SpotLight) {
             serializationObject.type = 2;
             serializationObject.type = 2;
-            serializationObject.position = light.position.asArray();
-            serializationObject.direction = light.position.asArray();
-            serializationObject.angle = light.angle;
-            serializationObject.exponent = light.exponent;
+            var spotLight = light;
+            serializationObject.position = spotLight.position.asArray();
+            serializationObject.direction = spotLight.position.asArray();
+            serializationObject.angle = spotLight.angle;
+            serializationObject.exponent = spotLight.exponent;
         } else if (light instanceof BABYLON.HemisphericLight) {
         } else if (light instanceof BABYLON.HemisphericLight) {
             serializationObject.type = 2;
             serializationObject.type = 2;
             serializationObject.groundColor = light.groundColor.asArray();
             serializationObject.groundColor = light.groundColor.asArray();
@@ -40,7 +38,7 @@ var BABYLON = BABYLON || {};
     var serializeCamera = function (camera) {
     var serializeCamera = function (camera) {
         var serializationObject = {};
         var serializationObject = {};
         serializationObject.name = camera.name;
         serializationObject.name = camera.name;
-        serializationObject.tags = camera._tags;
+        serializationObject.tags = BABYLON.Tags.GetTags(camera);
         serializationObject.id = camera.id;
         serializationObject.id = camera.id;
         serializationObject.position = camera.position.asArray();
         serializationObject.position = camera.position.asArray();
 
 
@@ -95,12 +93,13 @@ var BABYLON = BABYLON || {};
         serializationObject.property = animation.targetProperty;
         serializationObject.property = animation.targetProperty;
         serializationObject.framePerSecond = animation.framePerSecond;
         serializationObject.framePerSecond = animation.framePerSecond;
         serializationObject.dataType = animation.dataType;
         serializationObject.dataType = animation.dataType;
-        serializationObject.loopBehavior = animation.loopBehavior;
+        serializationObject.loopBehavior = animation.loopMode;
 
 
         var dataType = animation.dataType;
         var dataType = animation.dataType;
         serializationObject.keys = [];
         serializationObject.keys = [];
-        for (var index = 0; index < animation._keys.length; index++) {
-            var animationKey = animation._keys[index];
+        var keys = animation.getKeys();
+        for (var index = 0; index < keys.length; index++) {
+            var animationKey = keys[index];
 
 
             var key = {};
             var key = {};
             key.frame = animationKey.frame;
             key.frame = animationKey.frame;
@@ -127,7 +126,7 @@ var BABYLON = BABYLON || {};
 
 
         serializationObject.name = material.name;
         serializationObject.name = material.name;
         serializationObject.id = material.id;
         serializationObject.id = material.id;
-        serializationObject.tags = material._tags;
+        serializationObject.tags = BABYLON.Tags.GetTags(material);
 
 
         serializationObject.materials = [];
         serializationObject.materials = [];
 
 
@@ -158,7 +157,7 @@ var BABYLON = BABYLON || {};
         serializationObject.alpha = material.alpha;
         serializationObject.alpha = material.alpha;
 
 
         serializationObject.id = material.id;
         serializationObject.id = material.id;
-        serializationObject.tags = material._tags;
+        serializationObject.tags = BABYLON.Tags.GetTags(material);
         serializationObject.backFaceCulling = material.backFaceCulling;
         serializationObject.backFaceCulling = material.backFaceCulling;
 
 
         if (material.diffuseTexture) {
         if (material.diffuseTexture) {
@@ -209,20 +208,22 @@ var BABYLON = BABYLON || {};
         }
         }
 
 
         if (texture instanceof BABYLON.MirrorTexture) {
         if (texture instanceof BABYLON.MirrorTexture) {
-            serializationObject.renderTargetSize = texture.renderTargetSize;
+            var mirrorTexture = texture;
+            serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
             serializationObject.renderList = [];
             serializationObject.renderList = [];
 
 
-            for (var index = 0; index < texture.renderList.length; index++) {
-                serializationObject.renderList.push(texture.renderList[index].id);
+            for (var index = 0; index < mirrorTexture.renderList.length; index++) {
+                serializationObject.renderList.push(mirrorTexture.renderList[index].id);
             }
             }
 
 
-            serializationObject.mirrorPlane = texture.mirrorPlane.asArray();
+            serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
         } else if (texture instanceof BABYLON.RenderTargetTexture) {
         } else if (texture instanceof BABYLON.RenderTargetTexture) {
-            serializationObject.renderTargetSize = texture.renderTargetSize;
+            var renderTargetTexture = texture;
+            serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
             serializationObject.renderList = [];
             serializationObject.renderList = [];
 
 
-            for (var index = 0; index < texture.renderList.length; index++) {
-                serializationObject.renderList.push(texture.renderList[index].id);
+            for (index = 0; index < renderTargetTexture.renderList.length; index++) {
+                serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
             }
             }
         }
         }
 
 
@@ -261,9 +262,9 @@ var BABYLON = BABYLON || {};
             var bone = skeleton.bones[index];
             var bone = skeleton.bones[index];
 
 
             var serializedBone = {
             var serializedBone = {
-                parentBoneIndex: bone._parent ? bone._parent.id : -1,
+                parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
                 name: bone.name,
                 name: bone.name,
-                matrix: bone._matrix.toArray()
+                matrix: bone.getLocalMatrix().toArray()
             };
             };
 
 
             serializationObject.bones.push(serializedBone);
             serializationObject.bones.push(serializedBone);
@@ -279,7 +280,7 @@ var BABYLON = BABYLON || {};
         var serializationObject = {};
         var serializationObject = {};
 
 
         serializationObject.emitterId = particleSystem.emitter.id;
         serializationObject.emitterId = particleSystem.emitter.id;
-        serializationObject.capacity = particleSystem._capacity;
+        serializationObject.capacity = particleSystem.getCapacity();
 
 
         if (particleSystem.particleTexture) {
         if (particleSystem.particleTexture) {
             serializationObject.textureName = particleSystem.particleTexture.name;
             serializationObject.textureName = particleSystem.particleTexture.name;
@@ -301,7 +302,7 @@ var BABYLON = BABYLON || {};
         serializationObject.color2 = particleSystem.color2.asArray();
         serializationObject.color2 = particleSystem.color2.asArray();
         serializationObject.colorDead = particleSystem.colorDead.asArray();
         serializationObject.colorDead = particleSystem.colorDead.asArray();
         serializationObject.updateSpeed = particleSystem.updateSpeed;
         serializationObject.updateSpeed = particleSystem.updateSpeed;
-        serializationObject.targetStopDuration = particleSystem.targetStopFrame;
+        serializationObject.targetStopDuration = particleSystem.targetStopDuration;
         serializationObject.textureMask = particleSystem.textureMask.asArray();
         serializationObject.textureMask = particleSystem.textureMask.asArray();
         serializationObject.blendMode = particleSystem.blendMode;
         serializationObject.blendMode = particleSystem.blendMode;
 
 
@@ -311,7 +312,7 @@ var BABYLON = BABYLON || {};
     var serializeLensFlareSystem = function (lensFlareSystem) {
     var serializeLensFlareSystem = function (lensFlareSystem) {
         var serializationObject = {};
         var serializationObject = {};
 
 
-        serializationObject.emitterId = lensFlareSystem._emitter.id;
+        serializationObject.emitterId = lensFlareSystem.getEmitter().id;
         serializationObject.borderLimit = lensFlareSystem.borderLimit;
         serializationObject.borderLimit = lensFlareSystem.borderLimit;
 
 
         serializationObject.flares = [];
         serializationObject.flares = [];
@@ -326,16 +327,15 @@ var BABYLON = BABYLON || {};
             });
             });
         }
         }
 
 
-
         return serializationObject;
         return serializationObject;
     };
     };
 
 
     var serializeShadowGenerator = function (light) {
     var serializeShadowGenerator = function (light) {
         var serializationObject = {};
         var serializationObject = {};
-        var shadowGenerator = light._shadowGenerator;
+        var shadowGenerator = light.getShadowGenerator();
 
 
         serializationObject.lightId = light.id;
         serializationObject.lightId = light.id;
-        serializationObject.mapSize = shadowGenerator.getShadowMap()._size;
+        serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
         serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
         serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
 
 
         serializationObject.renderList = [];
         serializationObject.renderList = [];
@@ -353,7 +353,7 @@ var BABYLON = BABYLON || {};
 
 
         serializationObject.name = mesh.name;
         serializationObject.name = mesh.name;
         serializationObject.id = mesh.id;
         serializationObject.id = mesh.id;
-        serializationObject.tags = mesh._tags;
+        serializationObject.tags = BABYLON.Tags.GetTags(mesh);
 
 
         serializationObject.position = mesh.position.asArray();
         serializationObject.position = mesh.position.asArray();
 
 
@@ -459,8 +459,10 @@ var BABYLON = BABYLON || {};
         return serializationObject;
         return serializationObject;
     };
     };
 
 
-    BABYLON.SceneSerializer = {
-        Serialize: function (scene) {
+    var SceneSerializer = (function () {
+        function SceneSerializer() {
+        }
+        SceneSerializer.Serialize = function (scene) {
             var serializationObject = {};
             var serializationObject = {};
 
 
             // Scene
             // Scene
@@ -489,21 +491,21 @@ var BABYLON = BABYLON || {};
 
 
             // Cameras
             // Cameras
             serializationObject.cameras = [];
             serializationObject.cameras = [];
-            for (var index = 0; index < scene.cameras.length; index++) {
+            for (index = 0; index < scene.cameras.length; index++) {
                 var camera = scene.cameras[index];
                 var camera = scene.cameras[index];
 
 
                 if (camera instanceof BABYLON.FreeCamera) {
                 if (camera instanceof BABYLON.FreeCamera) {
                     serializationObject.cameras.push(serializeCamera(camera));
                     serializationObject.cameras.push(serializeCamera(camera));
                 }
                 }
             }
             }
-            if (scene.activecamera) {
+            if (scene.activeCamera) {
                 serializationObject.activeCameraID = scene.activeCamera.id;
                 serializationObject.activeCameraID = scene.activeCamera.id;
             }
             }
 
 
             // Materials
             // Materials
             serializationObject.materials = [];
             serializationObject.materials = [];
             serializationObject.multiMaterials = [];
             serializationObject.multiMaterials = [];
-            for (var index = 0; index < scene.materials.length; index++) {
+            for (index = 0; index < scene.materials.length; index++) {
                 var material = scene.materials[index];
                 var material = scene.materials[index];
 
 
                 if (material instanceof BABYLON.StandardMaterial) {
                 if (material instanceof BABYLON.StandardMaterial) {
@@ -515,13 +517,13 @@ var BABYLON = BABYLON || {};
 
 
             // Skeletons
             // Skeletons
             serializationObject.skeletons = [];
             serializationObject.skeletons = [];
-            for (var index = 0; index < scene.skeletons.length; index++) {
+            for (index = 0; index < scene.skeletons.length; index++) {
                 serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
                 serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
             }
             }
 
 
             // Meshes
             // Meshes
             serializationObject.meshes = [];
             serializationObject.meshes = [];
-            for (var index = 0; index < scene.meshes.length; index++) {
+            for (index = 0; index < scene.meshes.length; index++) {
                 var mesh = scene.meshes[index];
                 var mesh = scene.meshes[index];
 
 
                 if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
                 if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
@@ -531,27 +533,30 @@ var BABYLON = BABYLON || {};
 
 
             // Particles Systems
             // Particles Systems
             serializationObject.particleSystems = [];
             serializationObject.particleSystems = [];
-            for (var index = 0; index < scene.particleSystems.length; index++) {
+            for (index = 0; index < scene.particleSystems.length; index++) {
                 serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
                 serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
             }
             }
 
 
             // Lens flares
             // Lens flares
             serializationObject.lensFlareSystems = [];
             serializationObject.lensFlareSystems = [];
-            for (var index = 0; index < scene.lensFlareSystems.length; index++) {
+            for (index = 0; index < scene.lensFlareSystems.length; index++) {
                 serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
                 serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
             }
             }
 
 
             // Shadows
             // Shadows
             serializationObject.shadowGenerators = [];
             serializationObject.shadowGenerators = [];
-            for (var index = 0; index < scene.lights.length; index++) {
-                var light = scene.lights[index];
+            for (index = 0; index < scene.lights.length; index++) {
+                light = scene.lights[index];
 
 
-                if (light._shadowGenerator) {
+                if (light.getShadowGenerator()) {
                     serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
                     serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
                 }
                 }
             }
             }
 
 
             return serializationObject;
             return serializationObject;
-        }
-    };
-})();
+        };
+        return SceneSerializer;
+    })();
+    BABYLON.SceneSerializer = SceneSerializer;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.sceneSerializer.js.map

+ 559 - 0
Babylon/Tools/babylon.sceneSerializer.ts

@@ -0,0 +1,559 @@
+module BABYLON {
+
+    var serializeLight = (light: Light): any => {
+        var serializationObject:any = {};
+        serializationObject.name = light.name;
+        serializationObject.id = light.id;
+        serializationObject.tags = Tags.GetTags(light);
+
+        if (light instanceof BABYLON.PointLight) {
+            serializationObject.type = 0;
+            serializationObject.position = (<PointLight>light).position.asArray();
+        } else if (light instanceof BABYLON.DirectionalLight) {
+            serializationObject.type = 1;
+            var directionalLight = <DirectionalLight>light;
+            serializationObject.position = directionalLight.position.asArray();
+            serializationObject.direction = directionalLight.direction.asArray();
+        } else if (light instanceof BABYLON.SpotLight) {
+            serializationObject.type = 2;
+            var spotLight = <SpotLight>light;
+            serializationObject.position = spotLight.position.asArray();
+            serializationObject.direction = spotLight.position.asArray();
+            serializationObject.angle = spotLight.angle;
+            serializationObject.exponent = spotLight.exponent;
+        } else if (light instanceof BABYLON.HemisphericLight) {
+            serializationObject.type = 2;
+            serializationObject.groundColor = (<HemisphericLight>light).groundColor.asArray();
+        }
+
+        if (light.intensity) {
+            serializationObject.intensity = light.intensity;
+        }
+        serializationObject.diffuse = light.diffuse.asArray();
+        serializationObject.specular = light.specular.asArray();
+
+        return serializationObject;
+    };
+
+    var serializeCamera = (camera: FreeCamera): any => {
+        var serializationObject:any = {};
+        serializationObject.name = camera.name;
+        serializationObject.tags = Tags.GetTags(camera);
+        serializationObject.id = camera.id;
+        serializationObject.position = camera.position.asArray();
+
+        // Parent
+        if (camera.parent) {
+            serializationObject.parentId = camera.parent.id;
+        }
+
+        // Target
+        serializationObject.rotation = camera.rotation.asArray();
+
+        // Locked target
+        if (camera.lockedTarget && camera.lockedTarget.id) {
+            serializationObject.lockedTargetId = camera.lockedTarget.id;
+        }
+
+        serializationObject.fov = camera.fov;
+        serializationObject.minZ = camera.minZ;
+        serializationObject.maxZ = camera.maxZ;
+
+        serializationObject.speed = camera.speed;
+        serializationObject.inertia = camera.inertia;
+
+        serializationObject.checkCollisions = camera.checkCollisions;
+        serializationObject.applyGravity = camera.applyGravity;
+
+        if (camera.ellipsoid) {
+            serializationObject.ellipsoid = camera.ellipsoid.asArray();
+        }
+
+        // Animations
+        appendAnimations(camera, serializationObject);
+
+        return serializationObject;
+    };
+
+    var appendAnimations = (source: IAnimatable, destination: any): any => {
+        if (source.animations) {
+            destination.animations = [];
+            for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
+                var animation = source.animations[animationIndex];
+
+                destination.animations.push(serializeAnimation(animation));
+            }
+        }
+    };
+
+    var serializeAnimation = (animation: Animation): any => {
+        var serializationObject:any = {};
+
+        serializationObject.name = animation.name;
+        serializationObject.property = animation.targetProperty;
+        serializationObject.framePerSecond = animation.framePerSecond;
+        serializationObject.dataType = animation.dataType;
+        serializationObject.loopBehavior = animation.loopMode;
+
+        var dataType = animation.dataType;
+        serializationObject.keys = [];
+        var keys = animation.getKeys();
+        for (var index = 0; index < keys.length; index++) {
+            var animationKey = keys[index];
+
+            var key:any = {};
+            key.frame = animationKey.frame;
+
+            switch (dataType) {
+            case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
+                key.values = [animationKey.value];
+                break;
+            case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
+            case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
+            case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
+                key.values = animationKey.value.asArray();
+                break;
+            }
+
+            serializationObject.keys.push(key);
+        }
+
+        return serializationObject;
+    };
+
+    var serializeMultiMaterial = (material: MultiMaterial): any => {
+        var serializationObject:any = {};
+
+        serializationObject.name = material.name;
+        serializationObject.id = material.id;
+        serializationObject.tags = Tags.GetTags(material);
+
+        serializationObject.materials = [];
+
+        for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
+            var subMat = material.subMaterials[matIndex];
+
+            if (subMat) {
+                serializationObject.materials.push(subMat.id);
+            } else {
+                serializationObject.materials.push(null);
+            }
+        }
+
+        return serializationObject;
+    };
+
+    var serializeMaterial = (material: StandardMaterial): any => {
+        var serializationObject:any = {};
+
+        serializationObject.name = material.name;
+
+        serializationObject.ambient = material.ambientColor.asArray();
+        serializationObject.diffuse = material.diffuseColor.asArray();
+        serializationObject.specular = material.specularColor.asArray();
+        serializationObject.specularPower = material.specularPower;
+        serializationObject.emissive = material.emissiveColor.asArray();
+
+        serializationObject.alpha = material.alpha;
+
+        serializationObject.id = material.id;
+        serializationObject.tags = Tags.GetTags(material);
+        serializationObject.backFaceCulling = material.backFaceCulling;
+
+        if (material.diffuseTexture) {
+            serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
+        }
+
+        if (material.ambientTexture) {
+            serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
+        }
+
+        if (material.opacityTexture) {
+            serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
+        }
+
+        if (material.reflectionTexture) {
+            serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
+        }
+
+        if (material.emissiveTexture) {
+            serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
+        }
+
+        if (material.specularTexture) {
+            serializationObject.specularTexture = serializeTexture(material.specularTexture);
+        }
+
+        if (material.bumpTexture) {
+            serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
+        }
+
+        return serializationObject;
+    };
+
+    var serializeTexture = (texture: Texture): any => {
+        var serializationObject:any = {};
+
+        if (!texture.name) {
+            return null;
+        }
+
+        if (texture instanceof BABYLON.CubeTexture) {
+            serializationObject.name = texture.name;
+            serializationObject.hasAlpha = texture.hasAlpha;
+            serializationObject.level = texture.level;
+            serializationObject.coordinatesMode = texture.coordinatesMode;
+
+            return serializationObject;
+        }
+
+        if (texture instanceof BABYLON.MirrorTexture) {
+            var mirrorTexture = <MirrorTexture>texture;
+            serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
+            serializationObject.renderList = [];
+
+            for (var index = 0; index < mirrorTexture.renderList.length; index++) {
+                serializationObject.renderList.push(mirrorTexture.renderList[index].id);
+            }
+
+            serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
+        } else if (texture instanceof BABYLON.RenderTargetTexture) {
+            var renderTargetTexture = <RenderTargetTexture>texture;
+            serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
+            serializationObject.renderList = [];
+
+            for (index = 0; index < renderTargetTexture.renderList.length; index++) {
+                serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
+            }
+        }
+
+        serializationObject.name = texture.name;
+        serializationObject.hasAlpha = texture.hasAlpha;
+        serializationObject.level = texture.level;
+
+        serializationObject.coordinatesIndex = texture.coordinatesIndex;
+        serializationObject.coordinatesMode = texture.coordinatesMode;
+        serializationObject.uOffset = texture.uOffset;
+        serializationObject.vOffset = texture.vOffset;
+        serializationObject.uScale = texture.uScale;
+        serializationObject.vScale = texture.vScale;
+        serializationObject.uAng = texture.uAng;
+        serializationObject.vAng = texture.vAng;
+        serializationObject.wAng = texture.wAng;
+
+        serializationObject.wrapU = texture.wrapU;
+        serializationObject.wrapV = texture.wrapV;
+
+        // Animations
+        appendAnimations(texture, serializationObject);
+
+        return serializationObject;
+    };
+
+    var serializeSkeleton = (skeleton:Skeleton): any => {
+        var serializationObject:any = {};
+
+        serializationObject.name = skeleton.name;
+        serializationObject.id = skeleton.id;
+
+        serializationObject.bones = [];
+
+        for (var index = 0; index < skeleton.bones.length; index++) {
+            var bone = skeleton.bones[index];
+
+            var serializedBone:any = {
+                parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
+                name: bone.name,
+                matrix: bone.getLocalMatrix().toArray()
+            };
+
+            serializationObject.bones.push(serializedBone);
+
+            if (bone.animations && bone.animations.length > 0) {
+                serializedBone.animation = serializeAnimation(bone.animations[0]);
+            }
+        }
+        return serializationObject;
+    };
+
+    var serializeParticleSystem = (particleSystem:ParticleSystem): any => {
+        var serializationObject:any = {};
+
+        serializationObject.emitterId = particleSystem.emitter.id;
+        serializationObject.capacity = particleSystem.getCapacity();
+
+        if (particleSystem.particleTexture) {
+            serializationObject.textureName = particleSystem.particleTexture.name;
+        }
+
+        serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
+        serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
+        serializationObject.minSize = particleSystem.minSize;
+        serializationObject.maxSize = particleSystem.maxSize;
+        serializationObject.minLifeTime = particleSystem.minLifeTime;
+        serializationObject.maxLifeTime = particleSystem.maxLifeTime;
+        serializationObject.emitRate = particleSystem.emitRate;
+        serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
+        serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
+        serializationObject.gravity = particleSystem.gravity.asArray();
+        serializationObject.direction1 = particleSystem.direction1.asArray();
+        serializationObject.direction2 = particleSystem.direction2.asArray();
+        serializationObject.color1 = particleSystem.color1.asArray();
+        serializationObject.color2 = particleSystem.color2.asArray();
+        serializationObject.colorDead = particleSystem.colorDead.asArray();
+        serializationObject.updateSpeed = particleSystem.updateSpeed;
+        serializationObject.targetStopDuration = particleSystem.targetStopDuration;
+        serializationObject.textureMask = particleSystem.textureMask.asArray();
+        serializationObject.blendMode = particleSystem.blendMode;
+
+        return serializationObject;
+    };
+
+    var serializeLensFlareSystem = (lensFlareSystem:LensFlareSystem):any => {
+        var serializationObject:any = {};
+
+        serializationObject.emitterId = lensFlareSystem.getEmitter().id;
+        serializationObject.borderLimit = lensFlareSystem.borderLimit;
+
+        serializationObject.flares = [];
+        for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
+            var flare = lensFlareSystem.lensFlares[index];
+
+            serializationObject.flares.push({
+                size: flare.size,
+                position: flare.position,
+                color: flare.color.asArray(),
+                textureName: BABYLON.Tools.GetFilename(flare.texture.name)
+            });
+        }
+
+
+        return serializationObject;
+    };
+
+    var serializeShadowGenerator = (light: Light):any => {
+        var serializationObject:any = {};
+        var shadowGenerator = light.getShadowGenerator();
+
+        serializationObject.lightId = light.id;
+        serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
+        serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
+
+        serializationObject.renderList = [];
+        for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
+            var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
+
+            serializationObject.renderList.push(mesh.id);
+        }
+
+        return serializationObject;
+    };
+
+    var serializeMesh = (mesh: Mesh):any => {
+        var serializationObject:any = {};
+
+        serializationObject.name = mesh.name;
+        serializationObject.id = mesh.id;
+        serializationObject.tags = Tags.GetTags(mesh);
+
+        serializationObject.position = mesh.position.asArray();
+
+        if (mesh.rotation) {
+            serializationObject.rotation = mesh.rotation.asArray();
+        } else if (mesh.rotationQuaternion) {
+            serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
+        }
+
+        serializationObject.scaling = mesh.scaling.asArray();
+        serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
+
+        serializationObject.isEnabled = mesh.isEnabled();
+        serializationObject.isVisible = mesh.isVisible;
+        serializationObject.infiniteDistance = mesh.infiniteDistance;
+
+        serializationObject.receiveShadows = mesh.receiveShadows;
+
+        serializationObject.billboardMode = mesh.billboardMode;
+        serializationObject.visibility = mesh.visibility;
+
+        serializationObject.checkCollisions = mesh.checkCollisions;
+
+        // Parent
+        if (mesh.parent) {
+            serializationObject.parentId = mesh.parent.id;
+        }
+
+        // Geometry
+        if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
+            serializationObject.positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+            serializationObject.normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
+
+            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                serializationObject.uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
+            }
+
+            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
+                serializationObject.uvs2 = mesh.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
+            }
+
+            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
+                serializationObject.colors = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
+            }
+
+            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                serializationObject.matricesWeights = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
+            }
+
+            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
+                serializationObject.matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
+                serializationObject.matricesIndices._isExpanded = true;
+            }
+
+            serializationObject.indices = mesh.getIndices();
+
+            // SubMeshes
+            serializationObject.subMeshes = [];
+            for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                var subMesh = mesh.subMeshes[subIndex];
+
+                serializationObject.subMeshes.push({
+                    materialIndex: subMesh.materialIndex,
+                    verticesStart: subMesh.verticesStart,
+                    verticesCount: subMesh.verticesCount,
+                    indexStart: subMesh.indexStart,
+                    indexCount: subMesh.indexCount
+                });
+            }
+        }
+
+        // Material
+        if (mesh.material) {
+            serializationObject.materialId = mesh.material.id;
+        } else {
+            mesh.material = null;
+        }
+
+        // Skeleton
+        if (mesh.skeleton) {
+            serializationObject.skeletonId = mesh.skeleton.id;
+        }
+
+        // Physics
+        if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
+            serializationObject.physicsMass = mesh.getPhysicsMass();
+            serializationObject.physicsFriction = mesh.getPhysicsFriction();
+            serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
+
+            switch (mesh.getPhysicsImpostor()) {
+            case BABYLON.PhysicsEngine.BoxImpostor:
+                serializationObject.physicsImpostor = 1;
+                break;
+            case BABYLON.PhysicsEngine.SphereImpostor:
+                serializationObject.physicsImpostor = 2;
+                break;
+            }
+        }
+
+        // Animations
+        appendAnimations(mesh, serializationObject);
+
+        return serializationObject;
+    };
+
+
+    export class SceneSerializer {
+        public static Serialize(scene: Scene): any {
+            var serializationObject:any = {};
+
+            // Scene
+            serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
+            serializationObject.autoClear = scene.autoClear;
+            serializationObject.clearColor = scene.clearColor.asArray();
+            serializationObject.ambientColor = scene.ambientColor.asArray();
+            serializationObject.gravity = scene.gravity.asArray();
+
+            // Fog
+            if (scene.fogMode && scene.fogMode !== 0) {
+                serializationObject.fogMode = scene.fogMode;
+                serializationObject.fogColor = scene.fogColor.asArray();
+                serializationObject.fogStart = scene.fogStart;
+                serializationObject.fogEnd = scene.fogEnd;
+                serializationObject.fogDensity = scene.fogDensity;
+            }
+
+            // Lights
+            serializationObject.lights = [];
+            for (var index = 0; index < scene.lights.length; index++) {
+                var light = scene.lights[index];
+
+                serializationObject.lights.push(serializeLight(light));
+            }
+
+            // Cameras
+            serializationObject.cameras = [];
+            for (index = 0; index < scene.cameras.length; index++) {
+                var camera = scene.cameras[index];
+
+                if (camera instanceof BABYLON.FreeCamera) {
+                    serializationObject.cameras.push(serializeCamera(<FreeCamera>camera));
+                }
+            }
+            if (scene.activeCamera) {
+                serializationObject.activeCameraID = scene.activeCamera.id;
+            }
+
+            // Materials
+            serializationObject.materials = [];
+            serializationObject.multiMaterials = [];
+            for (index = 0; index < scene.materials.length; index++) {
+                var material = scene.materials[index];
+
+                if (material instanceof BABYLON.StandardMaterial) {
+                    serializationObject.materials.push(serializeMaterial(<StandardMaterial>material));
+                } else if (material instanceof BABYLON.MultiMaterial) {
+                    serializationObject.multiMaterials.push(serializeMultiMaterial(<MultiMaterial>material));
+                }
+            }
+
+            // Skeletons
+            serializationObject.skeletons = [];
+            for (index = 0; index < scene.skeletons.length; index++) {
+                serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
+            }
+
+            // Meshes
+            serializationObject.meshes = [];
+            for (index = 0; index < scene.meshes.length; index++) {
+                var mesh = scene.meshes[index];
+
+                if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
+                    serializationObject.meshes.push(serializeMesh(mesh));
+                }
+            }
+
+            // Particles Systems
+            serializationObject.particleSystems = [];
+            for (index = 0; index < scene.particleSystems.length; index++) {
+                serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
+            }
+
+            // Lens flares
+            serializationObject.lensFlareSystems = [];
+            for (index = 0; index < scene.lensFlareSystems.length; index++) {
+                serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
+            }
+
+            // Shadows
+            serializationObject.shadowGenerators = [];
+            for (index = 0; index < scene.lights.length; index++) {
+                light = scene.lights[index];
+
+                if (light.getShadowGenerator()) {
+                    serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
+                }
+            }
+
+            return serializationObject;
+        }
+    }
+}

+ 7 - 0
Babylon/Tools/babylon.tags.js

@@ -38,6 +38,13 @@
             return !BABYLON.Tools.IsEmpty(obj._tags);
             return !BABYLON.Tools.IsEmpty(obj._tags);
         };
         };
 
 
+        Tags.GetTags = function (obj) {
+            if (!obj._tags) {
+                return null;
+            }
+            return obj._tags;
+        };
+
         // the tags 'true' and 'false' are reserved and cannot be used as tags
         // the tags 'true' and 'false' are reserved and cannot be used as tags
         // a tag cannot start with '||', '&&', and '!'
         // a tag cannot start with '||', '&&', and '!'
         // it cannot contain whitespaces
         // it cannot contain whitespaces

+ 7 - 0
Babylon/Tools/babylon.tags.ts

@@ -35,6 +35,13 @@
             return !BABYLON.Tools.IsEmpty(obj._tags);
             return !BABYLON.Tools.IsEmpty(obj._tags);
         }
         }
 
 
+        public static GetTags(obj: any): any {
+            if (!obj._tags) {
+                return null;
+            }
+            return obj._tags;
+        }
+
         // the tags 'true' and 'false' are reserved and cannot be used as tags
         // the tags 'true' and 'false' are reserved and cannot be used as tags
         // a tag cannot start with '||', '&&', and '!'
         // a tag cannot start with '||', '&&', and '!'
         // it cannot contain whitespaces
         // it cannot contain whitespaces

+ 1 - 1
Babylon/Tools/babylon.tools.ts

@@ -252,7 +252,7 @@
             return -1.401298E-45 <= num && num <= 1.401298E-45;
             return -1.401298E-45 <= num && num <= 1.401298E-45;
         }
         }
 
 
-        public static DeepCopy(source, destination, doNotCopyList: string[], mustCopyList: string[]): void {
+        public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
             for (var prop in source) {
             for (var prop in source) {
 
 
                 if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
                 if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {

+ 169 - 172
Babylon/Tools/babylon.virtualJoystick.js

@@ -1,41 +1,31 @@
-/// <reference path="../../babylon.js" />
-
-// Mainly based on these 2 articles : 
+// Mainly based on these 2 articles :
 // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
 // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
-// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ 
-
-"use strict";
-
-// shim layer with setTimeout fallback
-window.requestAnimationFrame = (function () {
-    return window.requestAnimationFrame ||
-          window.webkitRequestAnimationFrame ||
-          window.mozRequestAnimationFrame ||
-          function (callback) {
-              window.setTimeout(callback, 1000 / 60);
-          };
-})();
-
+// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
+var BABYLON;
 (function (BABYLON) {
 (function (BABYLON) {
-    var VirtualJoystick = (function () {
-        var vjCanvas, vjCanvasContext, vjCanvasWidth, vjCanvasHeight, halfWidth, halfHeight;
-        var globalJoystickIndex = 0;
+    (function (JoystickAxis) {
+        JoystickAxis[JoystickAxis["X"] = 0] = "X";
+        JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
+        JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
+    })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
+    var JoystickAxis = BABYLON.JoystickAxis;
 
 
+    var VirtualJoystick = (function () {
         function VirtualJoystick(leftJoystick) {
         function VirtualJoystick(leftJoystick) {
+            var _this = this;
             if (leftJoystick) {
             if (leftJoystick) {
                 this._leftJoystick = true;
                 this._leftJoystick = true;
-            }
-            else {
+            } else {
                 this._leftJoystick = false;
                 this._leftJoystick = false;
             }
             }
 
 
-            this.joystickIndex = globalJoystickIndex;
-            globalJoystickIndex++;
+            this.joystickIndex = VirtualJoystick._globalJoystickIndex;
+            VirtualJoystick._globalJoystickIndex++;
 
 
             // By default left & right arrow keys are moving the X
             // By default left & right arrow keys are moving the X
             // and up & down keys are moving the Y
             // and up & down keys are moving the Y
-            this._axisTargetedByLeftAndRight = "X";
-            this._axisTargetedByUpAndDown = "Y";
+            this._axisTargetedByLeftAndRight = 0 /* X */;
+            this._axisTargetedByUpAndDown = 1 /* Y */;
 
 
             this.reverseLeftRight = false;
             this.reverseLeftRight = false;
             this.reverseUpDown = false;
             this.reverseUpDown = false;
@@ -50,69 +40,69 @@ window.requestAnimationFrame = (function () {
             this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
             this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
             this._rotateOnAxisRelativeToMesh = false;
             this._rotateOnAxisRelativeToMesh = false;
 
 
-            var that = this;
-
             // injecting a canvas element on top of the canvas 3D game
             // injecting a canvas element on top of the canvas 3D game
-            if (!vjCanvas) {
+            if (!VirtualJoystick.vjCanvas) {
                 window.addEventListener("resize", function () {
                 window.addEventListener("resize", function () {
-                    vjCanvasWidth = window.innerWidth;
-                    vjCanvasHeight = window.innerHeight;
-                    vjCanvas.width = vjCanvasWidth;
-                    vjCanvas.height = vjCanvasHeight;
-                    halfWidth = vjCanvasWidth / 2;
-                    halfHeight = vjCanvasHeight / 2;
+                    VirtualJoystick.vjCanvasWidth = window.innerWidth;
+                    VirtualJoystick.vjCanvasHeight = window.innerHeight;
+                    VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
+                    VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
+                    VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
+                    VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
                 }, false);
                 }, false);
-                vjCanvas = document.createElement("canvas");
-                vjCanvasWidth = window.innerWidth;
-                vjCanvasHeight = window.innerHeight;
-                vjCanvas.width = window.innerWidth;
-                vjCanvas.height = window.innerHeight;
-                vjCanvas.style.width = "100%";
-                vjCanvas.style.height = "100%";
-                vjCanvas.style.position = "absolute";
-                vjCanvas.style.backgroundColor = "transparent";
-                vjCanvas.style.top = "0px";
-                vjCanvas.style.left = "0px";
-                vjCanvas.style.zIndex = 5;
-                vjCanvas.style.msTouchAction = "none";
-                vjCanvasContext = vjCanvas.getContext('2d');
-                vjCanvasContext.strokeStyle = "#ffffff";
-                vjCanvasContext.lineWidth = 2;
-                document.body.appendChild(vjCanvas);
+                VirtualJoystick.vjCanvas = document.createElement("canvas");
+                VirtualJoystick.vjCanvasWidth = window.innerWidth;
+                VirtualJoystick.vjCanvasHeight = window.innerHeight;
+                VirtualJoystick.vjCanvas.width = window.innerWidth;
+                VirtualJoystick.vjCanvas.height = window.innerHeight;
+                VirtualJoystick.vjCanvas.style.width = "100%";
+                VirtualJoystick.vjCanvas.style.height = "100%";
+                VirtualJoystick.vjCanvas.style.position = "absolute";
+                VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
+                VirtualJoystick.vjCanvas.style.top = "0px";
+                VirtualJoystick.vjCanvas.style.left = "0px";
+                VirtualJoystick.vjCanvas.style.zIndex = "5";
+                VirtualJoystick.vjCanvas.style.msTouchAction = "none";
+                VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
+                VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
+                VirtualJoystick.vjCanvasContext.lineWidth = 2;
+                document.body.appendChild(VirtualJoystick.vjCanvas);
             }
             }
-            halfWidth = vjCanvas.width / 2;
-            halfHeight = vjCanvas.height / 2;
+            VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
+            VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
             this.pressed = false;
             this.pressed = false;
+
             // default joystick color
             // default joystick color
             this._joystickColor = "cyan";
             this._joystickColor = "cyan";
 
 
             this.joystickPointerID = -1;
             this.joystickPointerID = -1;
+
             // current joystick position
             // current joystick position
             this.joystickPointerPos = new BABYLON.Vector2(0, 0);
             this.joystickPointerPos = new BABYLON.Vector2(0, 0);
+
             // origin joystick position
             // origin joystick position
             this.joystickPointerStartPos = new BABYLON.Vector2(0, 0);
             this.joystickPointerStartPos = new BABYLON.Vector2(0, 0);
             this.deltaJoystickVector = new BABYLON.Vector2(0, 0);
             this.deltaJoystickVector = new BABYLON.Vector2(0, 0);
 
 
-            vjCanvas.addEventListener('pointerdown', function (evt) {
-                that.onPointerDown(evt);
+            VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
+                _this.onPointerDown(evt);
             }, false);
             }, false);
-            vjCanvas.addEventListener('pointermove', function (evt) {
-                that.onPointerMove(evt);
+            VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
+                _this.onPointerMove(evt);
             }, false);
             }, false);
-            vjCanvas.addEventListener('pointerup', function (evt) {
-                that.onPointerUp(evt);
+            VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
+                _this.onPointerUp(evt);
             }, false);
             }, false);
-            vjCanvas.addEventListener('pointerout', function (evt) {
-                that.onPointerUp(evt);
+            VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
+                _this.onPointerUp(evt);
             }, false);
             }, false);
-            vjCanvas.addEventListener("contextmenu", function (e) {
-                e.preventDefault();    // Disables system menu
+            VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
+                evt.preventDefault(); // Disables system menu
             }, false);
             }, false);
             requestAnimationFrame(function () {
             requestAnimationFrame(function () {
-                that.drawVirtualJoystick();
+                _this.drawVirtualJoystick();
             });
             });
         }
         }
-
         VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
         VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
             this._joystickSensibility = newJoystickSensibility;
             this._joystickSensibility = newJoystickSensibility;
             this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
             this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
@@ -123,10 +113,9 @@ window.requestAnimationFrame = (function () {
             var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: this.givePointerType(e) };
             var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: this.givePointerType(e) };
             var positionOnScreenCondition;
             var positionOnScreenCondition;
             if (this._leftJoystick === true) {
             if (this._leftJoystick === true) {
-                positionOnScreenCondition = (e.clientX < halfWidth);
-            }
-            else {
-                positionOnScreenCondition = (e.clientX > halfWidth);
+                positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
+            } else {
+                positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
             }
             }
 
 
             if (positionOnScreenCondition && this.joystickPointerID < 0) {
             if (positionOnScreenCondition && this.joystickPointerID < 0) {
@@ -138,13 +127,12 @@ window.requestAnimationFrame = (function () {
                 this.deltaJoystickVector.x = 0;
                 this.deltaJoystickVector.x = 0;
                 this.deltaJoystickVector.y = 0;
                 this.deltaJoystickVector.y = 0;
                 this.pressed = true;
                 this.pressed = true;
-                this._touches.add(e.pointerId, newPointer);
-            }
-            else {
+                this._touches.add(e.pointerId.toString(), newPointer);
+            } else {
                 // You can only trigger the action buttons with a joystick declared
                 // You can only trigger the action buttons with a joystick declared
-                if (globalJoystickIndex < 2 && this._action) {
+                if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
                     this._action();
                     this._action();
-                    this._touches.add(e.pointerId, newPointer);
+                    this._touches.add(e.pointerId.toString(), newPointer);
                 }
                 }
             }
             }
         };
         };
@@ -160,34 +148,33 @@ window.requestAnimationFrame = (function () {
                 var directionLeftRight = this.reverseLeftRight ? -1 : 1;
                 var directionLeftRight = this.reverseLeftRight ? -1 : 1;
                 var deltaJoystickX = directionLeftRight * this.deltaJoystickVector.x / this._inversedSensibility;
                 var deltaJoystickX = directionLeftRight * this.deltaJoystickVector.x / this._inversedSensibility;
                 switch (this._axisTargetedByLeftAndRight) {
                 switch (this._axisTargetedByLeftAndRight) {
-                    case "X":
+                    case 0 /* X */:
                         this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
                         this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
                         break;
                         break;
-                    case "Y":
+                    case 1 /* Y */:
                         this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
                         this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
                         break;
                         break;
-                    case "Z":
+                    case 2 /* Z */:
                         this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
                         this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
                         break;
                         break;
                 }
                 }
                 var directionUpDown = this.reverseUpDown ? 1 : -1;
                 var directionUpDown = this.reverseUpDown ? 1 : -1;
                 var deltaJoystickY = directionUpDown * this.deltaJoystickVector.y / this._inversedSensibility;
                 var deltaJoystickY = directionUpDown * this.deltaJoystickVector.y / this._inversedSensibility;
                 switch (this._axisTargetedByUpAndDown) {
                 switch (this._axisTargetedByUpAndDown) {
-                    case "X":
+                    case 0 /* X */:
                         this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
                         this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
                         break;
                         break;
-                    case "Y":
+                    case 1 /* Y */:
                         this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
                         this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
                         break;
                         break;
-                    case "Z":
+                    case 2 /* Z */:
                         this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
                         this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
                         break;
                         break;
                 }
                 }
-            }
-            else {
-                if (this._touches.item(e.pointerId)) {
-                    this._touches.item(e.pointerId).x = e.clientX;
-                    this._touches.item(e.pointerId).y = e.clientY;
+            } else {
+                if (this._touches.item(e.pointerId.toString())) {
+                    this._touches.item(e.pointerId.toString()).x = e.clientX;
+                    this._touches.item(e.pointerId.toString()).y = e.clientY;
                 }
                 }
             }
             }
         };
         };
@@ -200,7 +187,7 @@ window.requestAnimationFrame = (function () {
             this.deltaJoystickVector.x = 0;
             this.deltaJoystickVector.x = 0;
             this.deltaJoystickVector.y = 0;
             this.deltaJoystickVector.y = 0;
 
 
-            this._touches.remove(e.pointerId);
+            this._touches.remove(e.pointerId.toString());
         };
         };
 
 
         VirtualJoystick.prototype.setJoystickColor = function (newColor) {
         VirtualJoystick.prototype.setJoystickColor = function (newColor) {
@@ -211,72 +198,72 @@ window.requestAnimationFrame = (function () {
             this._action = action;
             this._action = action;
         };
         };
 
 
-        // Define which axis you'd like to control for left & right 
-        VirtualJoystick.prototype.setAxisForLR = function (axisLetter) {
-            switch (axisLetter) {
-                case "X":
-                case "Y":
-                case "Z":
-                    this._axisTargetedByLeftAndRight = axisLetter;
+        // Define which axis you'd like to control for left & right
+        VirtualJoystick.prototype.setAxisForLR = function (axis) {
+            switch (axis) {
+                case 0 /* X */:
+                case 1 /* Y */:
+                case 2 /* Z */:
+                    this._axisTargetedByLeftAndRight = axis;
+                    break;
+                    this._axisTargetedByLeftAndRight = axis;
                     break;
                     break;
                 default:
                 default:
-                    this._axisTargetedByLeftAndRight = "X";
+                    this._axisTargetedByLeftAndRight = 0 /* X */;
                     break;
                     break;
             }
             }
         };
         };
 
 
-        // Define which axis you'd like to control for up & down 
-        VirtualJoystick.prototype.setAxisForUD = function (axisLetter) {
-            switch (axisLetter) {
-                case "X":
-                case "Y":
-                case "Z":
-                    this._axisTargetedByUpAndDown = axisLetter;
+        // Define which axis you'd like to control for up & down
+        VirtualJoystick.prototype.setAxisForUD = function (axis) {
+            switch (axis) {
+                case 0 /* X */:
+                case 1 /* Y */:
+                case 2 /* Z */:
+                    this._axisTargetedByUpAndDown = axis;
                     break;
                     break;
                 default:
                 default:
-                    this._axisTargetedByUpAndDown = "Y";
+                    this._axisTargetedByUpAndDown = 1 /* Y */;
                     break;
                     break;
             }
             }
         };
         };
 
 
         VirtualJoystick.prototype.drawVirtualJoystick = function () {
         VirtualJoystick.prototype.drawVirtualJoystick = function () {
-            var that = this;
-
-            if (that._leftJoystick) {
-                vjCanvasContext.clearRect(0, 0, vjCanvasWidth / 2, vjCanvasHeight);
-            }
-            else {
-                vjCanvasContext.clearRect(vjCanvasWidth / 2, 0, vjCanvasWidth, vjCanvasHeight);
+            var _this = this;
+            if (this._leftJoystick) {
+                VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
+            } else {
+                VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
             }
             }
             this._touches.forEach(function (touch) {
             this._touches.forEach(function (touch) {
-                if (touch.identifier === that.joystickPointerID) {
-                    vjCanvasContext.beginPath();
-                    vjCanvasContext.strokeStyle = that._joystickColor;
-                    vjCanvasContext.lineWidth = 6;
-                    vjCanvasContext.arc(that.joystickPointerStartPos.x, that.joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
-                    vjCanvasContext.stroke();
-                    vjCanvasContext.beginPath();
-                    vjCanvasContext.strokeStyle = that._joystickColor;
-                    vjCanvasContext.lineWidth = 2;
-                    vjCanvasContext.arc(that.joystickPointerStartPos.x, that.joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
-                    vjCanvasContext.stroke();
-                    vjCanvasContext.beginPath();
-                    vjCanvasContext.strokeStyle = that._joystickColor;
-                    vjCanvasContext.arc(that.joystickPointerPos.x, that.joystickPointerPos.y, 40, 0, Math.PI * 2, true);
-                    vjCanvasContext.stroke();
+                if (touch.identifier === _this.joystickPointerID) {
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.lineWidth = 6;
+                    VirtualJoystick.vjCanvasContext.arc(_this.joystickPointerStartPos.x, _this.joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.lineWidth = 2;
+                    VirtualJoystick.vjCanvasContext.arc(_this.joystickPointerStartPos.x, _this.joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.arc(_this.joystickPointerPos.x, _this.joystickPointerPos.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                } else {
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.fillStyle = "white";
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = "red";
+                    VirtualJoystick.vjCanvasContext.lineWidth = 6;
+                    VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
                 }
                 }
-                else {
-                    vjCanvasContext.beginPath();
-                    vjCanvasContext.fillStyle = "white";
-                    vjCanvasContext.beginPath();
-                    vjCanvasContext.strokeStyle = "red";
-                    vjCanvasContext.lineWidth = "6";
-                    vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
-                    vjCanvasContext.stroke();
-                };
+                ;
             });
             });
             requestAnimationFrame(function () {
             requestAnimationFrame(function () {
-                that.drawVirtualJoystick();
+                _this.drawVirtualJoystick();
             });
             });
         };
         };
 
 
@@ -295,47 +282,57 @@ window.requestAnimationFrame = (function () {
         };
         };
 
 
         VirtualJoystick.prototype.releaseCanvas = function () {
         VirtualJoystick.prototype.releaseCanvas = function () {
-            if (vjCanvas) {
-                document.body.removeChild(vjCanvas);
-                vjCanvas = null;
-            };
+            if (VirtualJoystick.vjCanvas) {
+                document.body.removeChild(VirtualJoystick.vjCanvas);
+                VirtualJoystick.vjCanvas = null;
+            }
         };
         };
-
+        VirtualJoystick._globalJoystickIndex = 0;
         return VirtualJoystick;
         return VirtualJoystick;
     })();
     })();
     BABYLON.VirtualJoystick = VirtualJoystick;
     BABYLON.VirtualJoystick = VirtualJoystick;
+})(BABYLON || (BABYLON = {}));
 
 
-    var Collection = (function () {
-        function Collection() {
-            this.count = 0;
-            this.collection = {};
-        };
-        Collection.prototype.add = function (key, item) {
-            if (this.collection[key] != undefined) {
-                return undefined;
-            }
-            this.collection[key] = item;
-            return ++this.count;
-        };
-        Collection.prototype.remove = function (key) {
-            if (this.collection[key] == undefined) {
-                return undefined;
+var BABYLON;
+(function (BABYLON) {
+    (function (VirtualJoystick) {
+        var Collection = (function () {
+            function Collection() {
+                this.count = 0;
+                this.collection = new Array();
             }
             }
-            delete this.collection[key];
-            return --this.count;
-        };
-        Collection.prototype.item = function (key) {
-            return this.collection[key];
-        };
-        Collection.prototype.forEach = function (block) {
-            var key;
-            for (key in this.collection) {
-                if (this.collection.hasOwnProperty(key)) {
-                    block(this.collection[key]);
+            Collection.prototype.add = function (key, item) {
+                if (this.collection[key] != undefined) {
+                    return undefined;
                 }
                 }
-            }
-        };
-        return Collection;
-    })();
-    BABYLON.VirtualJoystick.Collection = Collection;
-})(BABYLON || (BABYLON = {}));
+                this.collection[key] = item;
+                return ++this.count;
+            };
+
+            Collection.prototype.remove = function (key) {
+                if (this.collection[key] == undefined) {
+                    return undefined;
+                }
+                delete this.collection[key];
+                return --this.count;
+            };
+
+            Collection.prototype.item = function (key) {
+                return this.collection[key];
+            };
+
+            Collection.prototype.forEach = function (block) {
+                var key;
+                for (key in this.collection) {
+                    if (this.collection.hasOwnProperty(key)) {
+                        block(this.collection[key]);
+                    }
+                }
+            };
+            return Collection;
+        })();
+        VirtualJoystick.Collection = Collection;
+    })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
+    var VirtualJoystick = BABYLON.VirtualJoystick;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.virtualJoystick.js.map

+ 360 - 0
Babylon/Tools/babylon.virtualJoystick.ts

@@ -0,0 +1,360 @@
+// Mainly based on these 2 articles : 
+// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
+// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ 
+
+module BABYLON {
+    export enum JoystickAxis {
+        X,
+        Y,
+        Z
+    }
+
+    export class VirtualJoystick {
+        private static _globalJoystickIndex: number = 0;
+        private static vjCanvas: HTMLCanvasElement;
+        private static vjCanvasContext: CanvasRenderingContext2D;
+        private static vjCanvasWidth: number;
+        private static vjCanvasHeight: number; 
+        private static halfWidth: number; 
+        private static halfHeight: number;
+
+        private _leftJoystick: boolean;
+        private joystickIndex: number;
+        public reverseLeftRight: boolean;
+        public reverseUpDown: boolean;
+        private _touches: BABYLON.VirtualJoystick.Collection<any>;
+        public deltaPosition: Vector3;
+        private _axisTargetedByLeftAndRight: JoystickAxis;
+        private _axisTargetedByUpAndDown: JoystickAxis; 
+        private _joystickSensibility: number;
+        private _inversedSensibility: number;
+        private _rotationSpeed: number;
+        private _inverseRotationSpeed: number;
+        private _rotateOnAxisRelativeToMesh: boolean;
+        private joystickPointerID: number;
+        private _joystickColor: string;
+        private joystickPointerPos: Vector2;
+        private joystickPointerStartPos: Vector2;
+        private deltaJoystickVector: Vector2;
+        public pressed: boolean;
+        private _action: () => any;
+
+        constructor(leftJoystick?: boolean) {
+            if (leftJoystick) {
+                this._leftJoystick = true;
+            }
+            else {
+                this._leftJoystick = false;
+            }
+
+            this.joystickIndex = VirtualJoystick._globalJoystickIndex;
+            VirtualJoystick._globalJoystickIndex++;
+
+            // By default left & right arrow keys are moving the X
+            // and up & down keys are moving the Y
+            this._axisTargetedByLeftAndRight = JoystickAxis.X;
+            this._axisTargetedByUpAndDown = JoystickAxis.Y;
+
+            this.reverseLeftRight = false;
+            this.reverseUpDown = false;
+
+            // collections of pointers
+            this._touches = new BABYLON.VirtualJoystick.Collection<any>();
+            this.deltaPosition = BABYLON.Vector3.Zero();
+
+            this._joystickSensibility = 25;
+            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
+            this._rotationSpeed = 25;
+            this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
+            this._rotateOnAxisRelativeToMesh = false;
+
+            // injecting a canvas element on top of the canvas 3D game
+            if (!VirtualJoystick.vjCanvas) {
+                window.addEventListener("resize", function () {
+                    VirtualJoystick.vjCanvasWidth = window.innerWidth;
+                    VirtualJoystick.vjCanvasHeight = window.innerHeight;
+                    VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
+                    VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
+                    VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
+                    VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
+                }, false);
+                VirtualJoystick.vjCanvas = document.createElement("canvas");
+                VirtualJoystick.vjCanvasWidth = window.innerWidth;
+                VirtualJoystick.vjCanvasHeight = window.innerHeight;
+                VirtualJoystick.vjCanvas.width = window.innerWidth;
+                VirtualJoystick.vjCanvas.height = window.innerHeight;
+                VirtualJoystick.vjCanvas.style.width = "100%";
+                VirtualJoystick.vjCanvas.style.height = "100%";
+                VirtualJoystick.vjCanvas.style.position = "absolute";
+                VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
+                VirtualJoystick.vjCanvas.style.top = "0px";
+                VirtualJoystick.vjCanvas.style.left = "0px";
+                VirtualJoystick.vjCanvas.style.zIndex = "5";
+                VirtualJoystick.vjCanvas.style.msTouchAction = "none";
+                VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
+                VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
+                VirtualJoystick.vjCanvasContext.lineWidth = 2;
+                document.body.appendChild(VirtualJoystick.vjCanvas);
+            }
+            VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
+            VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
+            this.pressed = false;
+            // default joystick color
+            this._joystickColor = "cyan";
+
+            this.joystickPointerID = -1;
+            // current joystick position
+            this.joystickPointerPos = new BABYLON.Vector2(0, 0);
+            // origin joystick position
+            this.joystickPointerStartPos = new BABYLON.Vector2(0, 0);
+            this.deltaJoystickVector = new BABYLON.Vector2(0, 0);
+
+            VirtualJoystick.vjCanvas.addEventListener('pointerdown', (evt) => {
+                this.onPointerDown(evt);
+            }, false);
+            VirtualJoystick.vjCanvas.addEventListener('pointermove', (evt) => {
+                this.onPointerMove(evt);
+            }, false);
+            VirtualJoystick.vjCanvas.addEventListener('pointerup',  (evt) => {
+                this.onPointerUp(evt);
+            }, false);
+            VirtualJoystick.vjCanvas.addEventListener('pointerout', (evt) => {
+                this.onPointerUp(evt);
+            }, false);
+            VirtualJoystick.vjCanvas.addEventListener("contextmenu", (evt) => {
+                evt.preventDefault();    // Disables system menu
+            }, false);
+            requestAnimationFrame(() => { this.drawVirtualJoystick(); });
+        }
+
+        public setJoystickSensibility (newJoystickSensibility: number) {
+            this._joystickSensibility = newJoystickSensibility;
+            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
+        }
+
+        private onPointerDown (e: PointerEvent) {
+            e.preventDefault();
+            var newPointer = { identifier: e.pointerId, x: e.clientX, y: e.clientY, type: this.givePointerType(e) };
+            var positionOnScreenCondition: boolean;
+            if (this._leftJoystick === true) {
+                positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
+            }
+            else {
+                positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
+            }
+
+            if (positionOnScreenCondition && this.joystickPointerID < 0) {
+                // First contact will be dedicated to the virtual joystick
+                this.joystickPointerID = e.pointerId;
+                this.joystickPointerStartPos.x = e.clientX;
+                this.joystickPointerStartPos.y = e.clientY;
+                this.joystickPointerPos = this.joystickPointerStartPos.clone();
+                this.deltaJoystickVector.x = 0;
+                this.deltaJoystickVector.y = 0;
+                this.pressed = true;
+                this._touches.add(e.pointerId.toString(), newPointer);
+            }
+            else {
+                // You can only trigger the action buttons with a joystick declared
+                if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
+                    this._action();
+                    this._touches.add(e.pointerId.toString(), newPointer);
+                }
+            }
+        }
+
+        private onPointerMove (e: PointerEvent) {
+            // If the current pointer is the one associated to the joystick (first touch contact)
+            if (this.joystickPointerID == e.pointerId) {
+                this.joystickPointerPos.x = e.clientX;
+                this.joystickPointerPos.y = e.clientY;
+                this.deltaJoystickVector = this.joystickPointerPos.clone();
+                this.deltaJoystickVector = this.deltaJoystickVector.subtract(this.joystickPointerStartPos);
+
+                var directionLeftRight = this.reverseLeftRight ? -1 : 1;
+                var deltaJoystickX = directionLeftRight * this.deltaJoystickVector.x / this._inversedSensibility;
+                switch (this._axisTargetedByLeftAndRight) {
+                    case JoystickAxis.X:
+                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
+                        break;
+                    case JoystickAxis.Y:
+                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
+                        break;
+                    case JoystickAxis.Z:
+                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
+                        break;
+                }
+                var directionUpDown = this.reverseUpDown ? 1 : -1;
+                var deltaJoystickY = directionUpDown * this.deltaJoystickVector.y / this._inversedSensibility;
+                switch (this._axisTargetedByUpAndDown) {
+                    case JoystickAxis.X:
+                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
+                        break;
+                    case JoystickAxis.Y:
+                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
+                        break;
+                    case JoystickAxis.Z:
+                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
+                        break;
+                }
+            }
+            else {
+                if (this._touches.item(e.pointerId.toString())) {
+                    this._touches.item(e.pointerId.toString()).x = e.clientX;
+                    this._touches.item(e.pointerId.toString()).y = e.clientY;
+                }
+            }
+        }
+
+       private onPointerUp (e: PointerEvent) {
+            if (this.joystickPointerID == e.pointerId) {
+                this.joystickPointerID = -1;
+                this.pressed = false;
+            }
+            this.deltaJoystickVector.x = 0;
+            this.deltaJoystickVector.y = 0;
+
+           this._touches.remove(e.pointerId.toString());
+        }
+
+        public setJoystickColor (newColor: string) {
+            this._joystickColor = newColor;
+        }
+
+        public setActionOnTouch (action: () => any) {
+            this._action = action;
+        }
+
+        // Define which axis you'd like to control for left & right 
+        public setAxisForLR(axis: JoystickAxis) {
+            switch (axis) {
+                case JoystickAxis.X:
+                case JoystickAxis.Y:
+                case JoystickAxis.Z:
+                    this._axisTargetedByLeftAndRight = axis;
+                    break;
+                    this._axisTargetedByLeftAndRight = axis;
+                    break;
+                default:
+                    this._axisTargetedByLeftAndRight = JoystickAxis.X;
+                    break;
+            }
+        }
+
+        // Define which axis you'd like to control for up & down 
+        public setAxisForUD(axis: JoystickAxis) {
+            switch (axis) {
+                case JoystickAxis.X:
+                case JoystickAxis.Y:
+                case JoystickAxis.Z:
+                    this._axisTargetedByUpAndDown = axis;
+                    break;
+                default:
+                    this._axisTargetedByUpAndDown = JoystickAxis.Y;
+                    break;
+            }
+        }
+
+        private drawVirtualJoystick () {
+            if (this._leftJoystick) {
+                VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
+            }
+            else {
+                VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
+            }
+            this._touches.forEach((touch) => {
+                if (touch.identifier === this.joystickPointerID) {
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.lineWidth = 6;
+                    VirtualJoystick.vjCanvasContext.arc(this.joystickPointerStartPos.x, this.joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.lineWidth = 2;
+                    VirtualJoystick.vjCanvasContext.arc(this.joystickPointerStartPos.x, this.joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
+                    VirtualJoystick.vjCanvasContext.arc(this.joystickPointerPos.x, this.joystickPointerPos.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                }
+                else {
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.fillStyle = "white";
+                    VirtualJoystick.vjCanvasContext.beginPath();
+                    VirtualJoystick.vjCanvasContext.strokeStyle = "red";
+                    VirtualJoystick.vjCanvasContext.lineWidth = 6;
+                    VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
+                    VirtualJoystick.vjCanvasContext.stroke();
+                };
+            });
+            requestAnimationFrame(() => { this.drawVirtualJoystick(); });
+        }
+
+        private givePointerType (event) {
+            switch (event.pointerType) {
+                case event.POINTER_TYPE_MOUSE:
+                    return "MOUSE";
+                    break;
+                case event.POINTER_TYPE_PEN:
+                    return "PEN";
+                    break;
+                case event.POINTER_TYPE_TOUCH:
+                    return "TOUCH";
+                    break;
+            }
+        }
+
+        public releaseCanvas () {
+            if (VirtualJoystick.vjCanvas) {
+                document.body.removeChild(VirtualJoystick.vjCanvas);
+                VirtualJoystick.vjCanvas = null;
+            }
+        }
+    }
+}
+
+module BABYLON.VirtualJoystick {
+    export class Collection<T> {
+        private count: number;
+        private collection: Array<T>;
+
+        constructor() {
+            this.count = 0;
+            this.collection = new Array<T>();
+        }
+
+        public add<T>(key: string, item: T): number {
+            if (this.collection[key] != undefined) {
+                return undefined;
+            }
+            this.collection[key] = item;
+            return ++this.count;
+        }
+
+        public remove(key: string): number {
+            if (this.collection[key] == undefined) {
+                return undefined;
+            }
+            delete this.collection[key];
+            return --this.count;
+        }
+
+        public item(key: string) {
+            return this.collection[key];
+        }
+
+        public forEach<T>(block: (T) => any) {
+            var key: string;
+            for (key in this.collection) {
+                if (this.collection.hasOwnProperty(key)) {
+                    block(this.collection[key]);
+                }
+            }
+        }
+    }
+}
+
+
+

+ 52 - 37
Babylon/babylon.engine.js

@@ -25,26 +25,25 @@
         return count;
         return count;
     };
     };
 
 
-    //ANY
-    var prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, processFunction) {
+    var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, processFunction) {
         var engine = scene.getEngine();
         var engine = scene.getEngine();
-        var potWidth = getExponantOfTwo(width, engine._caps.maxTextureSize);
-        var potHeight = getExponantOfTwo(height, engine._caps.maxTextureSize);
+        var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
+        var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
 
 
-        engine._gl.bindTexture(engine._gl.TEXTURE_2D, texture);
-        engine._gl.pixelStorei(engine._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? true : invertY);
+        gl.bindTexture(gl.TEXTURE_2D, texture);
+        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
 
 
         processFunction(potWidth, potHeight);
         processFunction(potWidth, potHeight);
 
 
-        engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MAG_FILTER, engine._gl.LINEAR);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
 
 
         if (noMipmap) {
         if (noMipmap) {
-            engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
         } else {
         } else {
-            engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR_MIPMAP_LINEAR);
-            engine._gl.generateMipmap(engine._gl.TEXTURE_2D);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
+            gl.generateMipmap(gl.TEXTURE_2D);
         }
         }
-        engine._gl.bindTexture(engine._gl.TEXTURE_2D, null);
+        gl.bindTexture(gl.TEXTURE_2D, null);
 
 
         engine._activeTexturesCache = [];
         engine._activeTexturesCache = [];
         texture._baseWidth = width;
         texture._baseWidth = width;
@@ -79,6 +78,13 @@
         scene._addPendingData(img);
         scene._addPendingData(img);
     };
     };
 
 
+    var EngineCapabilities = (function () {
+        function EngineCapabilities() {
+        }
+        return EngineCapabilities;
+    })();
+    BABYLON.EngineCapabilities = EngineCapabilities;
+
     var Engine = (function () {
     var Engine = (function () {
         function Engine(canvas, antialias, options) {
         function Engine(canvas, antialias, options) {
             var _this = this;
             var _this = this;
@@ -92,8 +98,8 @@
             this._windowIsBackground = false;
             this._windowIsBackground = false;
             this._runningLoop = false;
             this._runningLoop = false;
             // Cache
             // Cache
-            this._loadedTexturesCache = [];
-            this._activeTexturesCache = [];
+            this._loadedTexturesCache = new Array();
+            this._activeTexturesCache = new Array();
             this._compiledEffects = {};
             this._compiledEffects = {};
             this._lastVertexAttribIndex = 0;
             this._lastVertexAttribIndex = 0;
             this._depthMask = false;
             this._depthMask = false;
@@ -132,7 +138,7 @@
             this.resize();
             this.resize();
 
 
             // Caps
             // Caps
-            this._caps = {};
+            this._caps = new EngineCapabilities();
             this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
             this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
             this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
             this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
             this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
             this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
@@ -189,14 +195,22 @@
         }
         }
         Engine.prototype.getAspectRatio = function (camera) {
         Engine.prototype.getAspectRatio = function (camera) {
             var viewport = camera.viewport;
             var viewport = camera.viewport;
-            return (this._renderingCanvas.width * viewport.width) / (this._renderingCanvas.height * viewport.height);
+            return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
         };
         };
 
 
         Engine.prototype.getRenderWidth = function () {
         Engine.prototype.getRenderWidth = function () {
+            if (this._currentRenderTarget) {
+                return this._currentRenderTarget._width;
+            }
+
             return this._renderingCanvas.width;
             return this._renderingCanvas.width;
         };
         };
 
 
         Engine.prototype.getRenderHeight = function () {
         Engine.prototype.getRenderHeight = function () {
+            if (this._currentRenderTarget) {
+                return this._currentRenderTarget._height;
+            }
+
             return this._renderingCanvas.height;
             return this._renderingCanvas.height;
         };
         };
 
 
@@ -213,12 +227,10 @@
             return this._hardwareScalingLevel;
             return this._hardwareScalingLevel;
         };
         };
 
 
-        //ANY
         Engine.prototype.getLoadedTexturesCache = function () {
         Engine.prototype.getLoadedTexturesCache = function () {
             return this._loadedTexturesCache;
             return this._loadedTexturesCache;
         };
         };
 
 
-        //ANY
         Engine.prototype.getCaps = function () {
         Engine.prototype.getCaps = function () {
             return this._caps;
             return this._caps;
         };
         };
@@ -339,6 +351,8 @@
         };
         };
 
 
         Engine.prototype.bindFramebuffer = function (texture) {
         Engine.prototype.bindFramebuffer = function (texture) {
+            this._currentRenderTarget = texture;
+
             var gl = this._gl;
             var gl = this._gl;
             gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
             gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
             this._gl.viewport(0, 0, texture._width, texture._height);
             this._gl.viewport(0, 0, texture._width, texture._height);
@@ -347,6 +361,7 @@
         };
         };
 
 
         Engine.prototype.unBindFramebuffer = function (texture) {
         Engine.prototype.unBindFramebuffer = function (texture) {
+            this._currentRenderTarget = null;
             if (texture.generateMipMaps) {
             if (texture.generateMipMaps) {
                 var gl = this._gl;
                 var gl = this._gl;
                 gl.bindTexture(gl.TEXTURE_2D, texture);
                 gl.bindTexture(gl.TEXTURE_2D, texture);
@@ -412,7 +427,6 @@
             return vbo;
             return vbo;
         };
         };
 
 
-        //ANY
         Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
         Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
             if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
             if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
                 this._cachedVertexBuffers = vertexBuffer;
                 this._cachedVertexBuffers = vertexBuffer;
@@ -437,7 +451,6 @@
             }
             }
         };
         };
 
 
-        //ANY
         Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
         Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
             if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
             if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
                 this._cachedVertexBuffers = vertexBuffers;
                 this._cachedVertexBuffers = vertexBuffers;
@@ -509,11 +522,12 @@
             this._gl.attachShader(shaderProgram, vertexShader);
             this._gl.attachShader(shaderProgram, vertexShader);
             this._gl.attachShader(shaderProgram, fragmentShader);
             this._gl.attachShader(shaderProgram, fragmentShader);
 
 
-            this._gl.linkProgram(shaderProgram);
-
-            var error = this._gl.getProgramInfoLog(shaderProgram);
-            if (error) {
-                throw new Error(error);
+            var linked = this._gl.linkProgram(shaderProgram);
+            if (!linked) {
+                var error = this._gl.getProgramInfoLog(shaderProgram);
+                if (error) {
+                    throw new Error(error);
+                }
             }
             }
 
 
             this._gl.deleteShader(vertexShader);
             this._gl.deleteShader(vertexShader);
@@ -714,7 +728,6 @@
             this._cachedEffectForVertexBuffers = null;
             this._cachedEffectForVertexBuffers = null;
         };
         };
 
 
-        //ANY
         Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
         Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
             var _this = this;
             var _this = this;
             var texture = this._gl.createTexture();
             var texture = this._gl.createTexture();
@@ -732,13 +745,13 @@
 
 
                     var loadMipmap = info.mipmapCount > 1 && !noMipmap;
                     var loadMipmap = info.mipmapCount > 1 && !noMipmap;
 
 
-                    prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, function (potWidth, potHeight) {
+                    prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, function () {
                         BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, loadMipmap);
                         BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, loadMipmap);
                     });
                     });
                 }, null, scene.database, true);
                 }, null, scene.database, true);
             } else {
             } else {
                 var onload = function (img) {
                 var onload = function (img) {
-                    prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, function (potWidth, potHeight) {
+                    prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, function (potWidth, potHeight) {
                         var isPot = (img.width == potWidth && img.height == potHeight);
                         var isPot = (img.width == potWidth && img.height == potHeight);
                         if (!isPot) {
                         if (!isPot) {
                             _this._workingCanvas.width = potWidth;
                             _this._workingCanvas.width = potWidth;
@@ -914,8 +927,8 @@
             return texture;
             return texture;
         };
         };
 
 
-        //ANY
         Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
         Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
+            var _this = this;
             var gl = this._gl;
             var gl = this._gl;
 
 
             var texture = gl.createTexture();
             var texture = gl.createTexture();
@@ -924,13 +937,12 @@
             texture.references = 1;
             texture.references = 1;
             this._loadedTexturesCache.push(texture);
             this._loadedTexturesCache.push(texture);
 
 
-            var that = this;
             cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
             cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
-                var width = getExponantOfTwo(imgs[0].width, that._caps.maxCubemapTextureSize);
+                var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
                 var height = width;
                 var height = width;
 
 
-                that._workingCanvas.width = width;
-                that._workingCanvas.height = height;
+                _this._workingCanvas.width = width;
+                _this._workingCanvas.height = height;
 
 
                 var faces = [
                 var faces = [
                     gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                     gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
@@ -941,8 +953,8 @@
                 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
 
 
                 for (var index = 0; index < faces.length; index++) {
                 for (var index = 0; index < faces.length; index++) {
-                    that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
-                    gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
+                    _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
+                    gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
                 }
                 }
 
 
                 if (!noMipmap) {
                 if (!noMipmap) {
@@ -956,7 +968,7 @@
 
 
                 gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
                 gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
 
 
-                that._activeTexturesCache = [];
+                _this._activeTexturesCache = [];
 
 
                 texture._width = width;
                 texture._width = width;
                 texture._height = height;
                 texture._height = height;
@@ -1052,8 +1064,11 @@
 
 
                 if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                 if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                     internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
                     internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
-                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
-                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
+
+                    // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE.  All other modes use REPEAT.
+                    var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
+                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
+                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
                 }
                 }
 
 
                 this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
                 this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);

+ 69 - 50
Babylon/babylon.engine.ts

@@ -24,27 +24,26 @@
         return count;
         return count;
     };
     };
 
 
-    //ANY
-    var prepareWebGLTexture = (texture: WebGLTexture, scene, width: number, height: number, invertY: boolean, noMipmap: boolean,
+    var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean,
         processFunction: (width: number, height: number) => void) => {
         processFunction: (width: number, height: number) => void) => {
         var engine = scene.getEngine();
         var engine = scene.getEngine();
-        var potWidth = getExponantOfTwo(width, engine._caps.maxTextureSize);
-        var potHeight = getExponantOfTwo(height, engine._caps.maxTextureSize);
+        var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
+        var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
 
 
-        engine._gl.bindTexture(engine._gl.TEXTURE_2D, texture);
-        engine._gl.pixelStorei(engine._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? true : invertY);
+        gl.bindTexture(gl.TEXTURE_2D, texture);
+        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
 
 
         processFunction(potWidth, potHeight);
         processFunction(potWidth, potHeight);
 
 
-        engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MAG_FILTER, engine._gl.LINEAR);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
 
 
         if (noMipmap) {
         if (noMipmap) {
-            engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
         } else {
         } else {
-            engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR_MIPMAP_LINEAR);
-            engine._gl.generateMipmap(engine._gl.TEXTURE_2D);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
+            gl.generateMipmap(gl.TEXTURE_2D);
         }
         }
-        engine._gl.bindTexture(engine._gl.TEXTURE_2D, null);
+        gl.bindTexture(gl.TEXTURE_2D, null);
 
 
         engine._activeTexturesCache = [];
         engine._activeTexturesCache = [];
         texture._baseWidth = width;
         texture._baseWidth = width;
@@ -80,6 +79,18 @@
         scene._addPendingData(img);
         scene._addPendingData(img);
     };
     };
 
 
+    export class EngineCapabilities {
+        public maxTexturesImageUnits: number;
+        public maxTextureSize: number;
+        public maxCubemapTextureSize: number;
+        public maxRenderTextureSize: number;
+        public standardDerivatives: boolean;
+        public s3tc;
+        public textureFloat: boolean;
+        public textureAnisotropicFilterExtension;
+        public maxAnisotropy: number;
+    }
+
     export class Engine {
     export class Engine {
         // Statics
         // Statics
         public static ShadersRepository = "Babylon/Shaders/";
         public static ShadersRepository = "Babylon/Shaders/";
@@ -115,7 +126,7 @@
         private _onPointerLockChange: () => void;
         private _onPointerLockChange: () => void;
 
 
         private _hardwareScalingLevel: number;
         private _hardwareScalingLevel: number;
-        private _caps; //ANY create a caps class
+        private _caps: EngineCapabilities;
         private _pointerLockRequested: boolean;
         private _pointerLockRequested: boolean;
         private _alphaTest: boolean;
         private _alphaTest: boolean;
 
 
@@ -123,9 +134,9 @@
         private _renderFunction: () => void;
         private _renderFunction: () => void;
 
 
         // Cache
         // Cache
-        private _loadedTexturesCache = []; //ANY
-        private _activeTexturesCache = []; //ANY
-        private _currentEffect; //ANY
+        private _loadedTexturesCache = new Array <WebGLTexture>();
+        public _activeTexturesCache = new Array<Texture>();
+        private _currentEffect: Effect;
         private _cullingState: boolean;
         private _cullingState: boolean;
         private _compiledEffects = {};
         private _compiledEffects = {};
         private _lastVertexAttribIndex = 0;
         private _lastVertexAttribIndex = 0;
@@ -133,7 +144,8 @@
         private _cachedViewport: Viewport;
         private _cachedViewport: Viewport;
         private _cachedVertexBuffers: any;
         private _cachedVertexBuffers: any;
         private _cachedIndexBuffer: WebGLBuffer;
         private _cachedIndexBuffer: WebGLBuffer;
-        private _cachedEffectForVertexBuffers; //ANY
+        private _cachedEffectForVertexBuffers: Effect;
+        private _currentRenderTarget: WebGLTexture;
 
 
         private _workingCanvas: HTMLCanvasElement;
         private _workingCanvas: HTMLCanvasElement;
         private _workingContext: CanvasRenderingContext2D;
         private _workingContext: CanvasRenderingContext2D;
@@ -176,7 +188,7 @@
             this.resize();
             this.resize();
 
 
             // Caps
             // Caps
-            this._caps = {};
+            this._caps = new EngineCapabilities();
             this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
             this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
             this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
             this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
             this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
             this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
@@ -242,14 +254,22 @@
 
 
         public getAspectRatio(camera: Camera): number {
         public getAspectRatio(camera: Camera): number {
             var viewport = camera.viewport;
             var viewport = camera.viewport;
-            return (this._renderingCanvas.width * viewport.width) / (this._renderingCanvas.height * viewport.height);
+            return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
         }
         }
 
 
         public getRenderWidth(): number {
         public getRenderWidth(): number {
+            if (this._currentRenderTarget) {
+                return this._currentRenderTarget._width;
+            }
+
             return this._renderingCanvas.width;
             return this._renderingCanvas.width;
         }
         }
 
 
         public getRenderHeight(): number {
         public getRenderHeight(): number {
+            if (this._currentRenderTarget) {
+                return this._currentRenderTarget._height;
+            }
+
             return this._renderingCanvas.height;
             return this._renderingCanvas.height;
         }
         }
 
 
@@ -266,13 +286,11 @@
             return this._hardwareScalingLevel;
             return this._hardwareScalingLevel;
         }
         }
 
 
-        //ANY
-        public getLoadedTexturesCache() {
+        public getLoadedTexturesCache():  WebGLTexture[] {
             return this._loadedTexturesCache;
             return this._loadedTexturesCache;
         }
         }
 
 
-        //ANY
-        public getCaps() {
+        public getCaps(): EngineCapabilities {
             return this._caps;
             return this._caps;
         }
         }
 
 
@@ -390,6 +408,8 @@
         }
         }
 
 
         public bindFramebuffer(texture: WebGLTexture): void {
         public bindFramebuffer(texture: WebGLTexture): void {
+            this._currentRenderTarget = texture;
+
             var gl = this._gl;
             var gl = this._gl;
             gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
             gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
             this._gl.viewport(0, 0, texture._width, texture._height);
             this._gl.viewport(0, 0, texture._width, texture._height);
@@ -398,6 +418,7 @@
         }
         }
 
 
         public unBindFramebuffer(texture: WebGLTexture): void {
         public unBindFramebuffer(texture: WebGLTexture): void {
+            this._currentRenderTarget = null;
             if (texture.generateMipMaps) {
             if (texture.generateMipMaps) {
                 var gl = this._gl;
                 var gl = this._gl;
                 gl.bindTexture(gl.TEXTURE_2D, texture);
                 gl.bindTexture(gl.TEXTURE_2D, texture);
@@ -439,7 +460,7 @@
             return vbo;
             return vbo;
         }
         }
 
 
-        public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length: number): void {
+        public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
             this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
             this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
             if (length && length != vertices.length) {
             if (length && length != vertices.length) {
                 this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
                 this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
@@ -463,8 +484,7 @@
             return vbo;
             return vbo;
         }
         }
 
 
-        //ANY
-        public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect): void {
+        public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
             if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
             if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
                 this._cachedVertexBuffers = vertexBuffer;
                 this._cachedVertexBuffers = vertexBuffer;
                 this._cachedEffectForVertexBuffers = effect;
                 this._cachedEffectForVertexBuffers = effect;
@@ -488,8 +508,7 @@
             }
             }
         }
         }
 
 
-        //ANY
-        public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect): void {
+        public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
             if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
             if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
                 this._cachedVertexBuffers = vertexBuffers;
                 this._cachedVertexBuffers = vertexBuffers;
                 this._cachedEffectForVertexBuffers = effect;
                 this._cachedEffectForVertexBuffers = effect;
@@ -536,8 +555,8 @@
             }
             }
         }
         }
 
 
-        public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines: string,
-            onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void): Effect {
+        public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
+            onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
             var vertex = baseName.vertexElement || baseName.vertex || baseName;
             var vertex = baseName.vertexElement || baseName.vertex || baseName;
             var fragment = baseName.fragmentElement || baseName.fragment || baseName;
             var fragment = baseName.fragmentElement || baseName.fragment || baseName;
 
 
@@ -561,11 +580,12 @@
             this._gl.attachShader(shaderProgram, vertexShader);
             this._gl.attachShader(shaderProgram, vertexShader);
             this._gl.attachShader(shaderProgram, fragmentShader);
             this._gl.attachShader(shaderProgram, fragmentShader);
 
 
-            this._gl.linkProgram(shaderProgram);
-
-            var error = this._gl.getProgramInfoLog(shaderProgram);
-            if (error) {
-                throw new Error(error);
+            var linked = this._gl.linkProgram(shaderProgram);
+            if (!linked) {
+                var error = this._gl.getProgramInfoLog(shaderProgram);
+                if (error) {
+                    throw new Error(error);
+                }
             }
             }
 
 
             this._gl.deleteShader(vertexShader);
             this._gl.deleteShader(vertexShader);
@@ -766,8 +786,7 @@
             this._cachedEffectForVertexBuffers = null;
             this._cachedEffectForVertexBuffers = null;
         }
         }
 
 
-        //ANY
-        public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene): WebGLTexture {
+        public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
             var texture = this._gl.createTexture();
             var texture = this._gl.createTexture();
             var isDDS = this.getCaps().s3tc && (url.substr(url.length - 4, 4).toLowerCase() === ".dds");
             var isDDS = this.getCaps().s3tc && (url.substr(url.length - 4, 4).toLowerCase() === ".dds");
 
 
@@ -783,13 +802,13 @@
 
 
                     var loadMipmap = info.mipmapCount > 1 && !noMipmap;
                     var loadMipmap = info.mipmapCount > 1 && !noMipmap;
 
 
-                    prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, (potWidth, potHeight) => {
+                    prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, () => {
                         BABYLON.Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
                         BABYLON.Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
                     });
                     });
                 }, null, scene.database, true);
                 }, null, scene.database, true);
             } else {
             } else {
                 var onload = (img) => {
                 var onload = (img) => {
-                    prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, (potWidth, potHeight) => {
+                    prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, (potWidth, potHeight) => {
                         var isPot = (img.width == potWidth && img.height == potHeight);
                         var isPot = (img.width == potWidth && img.height == potHeight);
                         if (!isPot) {
                         if (!isPot) {
                             this._workingCanvas.width = potWidth;
                             this._workingCanvas.width = potWidth;
@@ -964,8 +983,7 @@
             return texture;
             return texture;
         }
         }
 
 
-        //ANY
-        public createCubeTexture(rootUrl: string, scene, extensions: string[], noMipmap: boolean): WebGLTexture {
+        public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
             var gl = this._gl;
             var gl = this._gl;
 
 
             var texture = gl.createTexture();
             var texture = gl.createTexture();
@@ -974,13 +992,12 @@
             texture.references = 1;
             texture.references = 1;
             this._loadedTexturesCache.push(texture);
             this._loadedTexturesCache.push(texture);
 
 
-            var that = this;
-            cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
-                var width = getExponantOfTwo(imgs[0].width, that._caps.maxCubemapTextureSize);
+            cascadeLoad(rootUrl, 0, [], scene, imgs => {
+                var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
                 var height = width;
                 var height = width;
 
 
-                that._workingCanvas.width = width;
-                that._workingCanvas.height = height;
+                this._workingCanvas.width = width;
+                this._workingCanvas.height = height;
 
 
                 var faces = [
                 var faces = [
                     gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                     gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
@@ -991,8 +1008,8 @@
                 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
 
 
                 for (var index = 0; index < faces.length; index++) {
                 for (var index = 0; index < faces.length; index++) {
-                    that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
-                    gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
+                    this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
+                    gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
                 }
                 }
 
 
                 if (!noMipmap) {
                 if (!noMipmap) {
@@ -1006,7 +1023,7 @@
 
 
                 gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
                 gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
 
 
-                that._activeTexturesCache = [];
+                this._activeTexturesCache = [];
 
 
                 texture._width = width;
                 texture._width = width;
                 texture._height = height;
                 texture._height = height;
@@ -1103,8 +1120,10 @@
 
 
                 if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                 if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                     internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
                     internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
-                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
-                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
+                    // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE.  All other modes use REPEAT.
+                    var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
+                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
+                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
                 }
                 }
 
 
                 this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
                 this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);

+ 16 - 0
Babylon/babylon.mixins.ts

@@ -4,6 +4,7 @@ interface Window {
     mozRequestAnimationFrame(func: any): any;
     mozRequestAnimationFrame(func: any): any;
     oRequestAnimationFrame(func: any): any;
     oRequestAnimationFrame(func: any): any;
     WebGLRenderingContext: WebGLRenderingContext;
     WebGLRenderingContext: WebGLRenderingContext;
+    MSGesture: MSGesture;
 }
 }
 
 
 interface Document {
 interface Document {
@@ -35,6 +36,7 @@ interface WebGLTexture {
     noMipmap: boolean;
     noMipmap: boolean;
     references: number;
     references: number;
     generateMipMaps: boolean;
     generateMipMaps: boolean;
+    _size: number;
     _baseWidth: number;
     _baseWidth: number;
     _baseHeight: number;
     _baseHeight: number;
     _width: number;
     _width: number;
@@ -43,8 +45,22 @@ interface WebGLTexture {
     _workingContext: CanvasRenderingContext2D;
     _workingContext: CanvasRenderingContext2D;
     _framebuffer: WebGLFramebuffer;
     _framebuffer: WebGLFramebuffer;
     _depthBuffer: WebGLRenderbuffer;
     _depthBuffer: WebGLRenderbuffer;
+    _cachedCoordinatesMode: number;
+    _cachedWrapU: number;
+    _cachedWrapV: number;
 }
 }
 
 
 interface WebGLBuffer {
 interface WebGLBuffer {
     references: number;
     references: number;
+}
+
+interface MouseEvent {
+    movementX: number;
+    movementY: number;
+    mozMovementX: number;
+    mozMovementY: number;
+    webkitMovementX: number;
+    webkitMovementY: number;
+    msMovementX: number;
+    msMovementY: number;
 }
 }

+ 0 - 2
Babylon/babylon.node.js

@@ -12,12 +12,10 @@
             this._scene = scene;
             this._scene = scene;
             this._initCache();
             this._initCache();
         }
         }
-        //ANY
         Node.prototype.getScene = function () {
         Node.prototype.getScene = function () {
             return this._scene;
             return this._scene;
         };
         };
 
 
-        //ANY
         Node.prototype.getEngine = function () {
         Node.prototype.getEngine = function () {
             return this._scene.getEngine();
             return this._scene.getEngine();
         };
         };

+ 0 - 0
Babylon/babylon.node.ts


Деякі файли не було показано, через те що забагато файлів було змінено