Selaa lähdekoodia

cameras with composable inputs

gleborgne 9 vuotta sitten
vanhempi
commit
60f528020e
100 muutettua tiedostoa jossa 46655 lisäystä ja 47211 poistoa
  1. 9 10
      Tools/Gulp/config.json
  2. 30 21
      dist/preview release/babylon.core.js
  3. 175 73
      dist/preview release/babylon.d.ts
  4. 35 29
      dist/preview release/babylon.js
  5. 27907 28114
      dist/preview release/babylon.max.js
  6. 39 28
      dist/preview release/babylon.noworker.js
  7. 72 72
      src/Actions/babylon.action.js
  8. 473 473
      src/Actions/babylon.actionManager.js
  9. 117 117
      src/Actions/babylon.condition.js
  10. 204 204
      src/Actions/babylon.directActions.js
  11. 65 65
      src/Actions/babylon.interpolateValueAction.js
  12. 132 132
      src/Animations/babylon.animatable.js
  13. 671 671
      src/Animations/babylon.animation.js
  14. 249 249
      src/Animations/babylon.easing.js
  15. 111 111
      src/Audio/babylon.analyser.js
  16. 106 106
      src/Audio/babylon.audioEngine.js
  17. 552 552
      src/Audio/babylon.sound.js
  18. 101 101
      src/Audio/babylon.soundtrack.js
  19. 129 129
      src/Bones/babylon.bone.js
  20. 265 265
      src/Bones/babylon.skeleton.js
  21. 0 123
      src/Cameras/Composable/babylon.composableCamera.js
  22. 0 135
      src/Cameras/Composable/babylon.composableCamera.ts
  23. 12 12
      src/Cameras/Composable/Inputs/babylon.camerainput.deviceorientation.js
  24. 3 3
      src/Cameras/Composable/Inputs/babylon.camerainput.deviceorientation.ts
  25. 11 11
      src/Cameras/Composable/Inputs/babylon.camerainput.gamepad.js
  26. 3 3
      src/Cameras/Composable/Inputs/babylon.camerainput.gamepad.ts
  27. 13 13
      src/Cameras/Composable/Inputs/babylon.camerainput.keyboard.js
  28. 3 3
      src/Cameras/Composable/Inputs/babylon.camerainput.keyboard.ts
  29. 10 10
      src/Cameras/Composable/Inputs/babylon.camerainput.mouse.js
  30. 3 3
      src/Cameras/Composable/Inputs/babylon.camerainput.mouse.ts
  31. 18 12
      src/Cameras/Composable/Inputs/babylon.camerainput.touch.js
  32. 12 6
      src/Cameras/Composable/Inputs/babylon.camerainput.touch.ts
  33. 10 10
      src/Cameras/Composable/Inputs/babylon.camerainput.virtualjoystick.js
  34. 3 3
      src/Cameras/Composable/Inputs/babylon.camerainput.virtualjoystick.ts
  35. 72 72
      src/Cameras/VR/babylon.vrCameraMetrics.js
  36. 50 50
      src/Cameras/VR/babylon.vrDeviceOrientationCamera.js
  37. 76 76
      src/Cameras/VR/babylon.webVRCamera.js
  38. 672 672
      src/Cameras/babylon.arcRotateCamera.js
  39. 612 612
      src/Cameras/babylon.camera.js
  40. 10 33
      src/Cameras/Composable/babylon.cameraInputsManager.js
  41. 16 43
      src/Cameras/Composable/babylon.cameraInputsManager.ts
  42. 91 86
      src/Cameras/babylon.deviceOrientationCamera.js
  43. 71 71
      src/Cameras/babylon.deviceOrientationCamera.ts
  44. 117 117
      src/Cameras/babylon.followCamera.js
  45. 157 261
      src/Cameras/babylon.freeCamera.js
  46. 61 173
      src/Cameras/babylon.freeCamera.ts
  47. 21 21
      src/Cameras/babylon.gamepadCamera.js
  48. 116 116
      src/Cameras/babylon.stereoscopicCameras.js
  49. 264 264
      src/Cameras/babylon.targetCamera.js
  50. 162 134
      src/Cameras/babylon.touchCamera.js
  51. 143 142
      src/Cameras/babylon.touchCamera.ts
  52. 73 72
      src/Cameras/babylon.universalCamera.js
  53. 53 52
      src/Cameras/babylon.universalCamera.ts
  54. 54 54
      src/Cameras/babylon.virtualJoysticksCamera.js
  55. 272 272
      src/Collisions/babylon.collider.js
  56. 273 273
      src/Collisions/babylon.collisionCoordinator.js
  57. 243 243
      src/Collisions/babylon.collisionWorker.js
  58. 76 76
      src/Collisions/babylon.pickingInfo.js
  59. 88 88
      src/Culling/Octrees/babylon.octree.js
  60. 122 122
      src/Culling/Octrees/babylon.octreeBlock.js
  61. 143 143
      src/Culling/babylon.boundingBox.js
  62. 119 119
      src/Culling/babylon.boundingInfo.js
  63. 49 49
      src/Culling/babylon.boundingSphere.js
  64. 171 171
      src/Culling/babylon.ray.js
  65. 665 665
      src/Debug/babylon.debugLayer.js
  66. 137 137
      src/Debug/babylon.skeletonViewer.js
  67. 95 95
      src/Layer/babylon.layer.js
  68. 23 23
      src/LensFlare/babylon.lensFlare.js
  69. 208 208
      src/LensFlare/babylon.lensFlareSystem.js
  70. 405 405
      src/Lights/Shadows/babylon.shadowGenerator.js
  71. 129 129
      src/Lights/babylon.directionalLight.js
  72. 51 51
      src/Lights/babylon.hemisphericLight.js
  73. 162 162
      src/Lights/babylon.light.js
  74. 87 87
      src/Lights/babylon.pointLight.js
  75. 98 98
      src/Lights/babylon.spotLight.js
  76. 412 412
      src/Loading/Plugins/babylon.babylonFileLoader.js
  77. 186 186
      src/Loading/babylon.sceneLoader.js
  78. 124 124
      src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js
  79. 276 276
      src/Materials/Textures/Procedurals/babylon.proceduralTexture.js
  80. 138 138
      src/Materials/Textures/babylon.baseTexture.js
  81. 96 96
      src/Materials/Textures/babylon.cubeTexture.js
  82. 93 93
      src/Materials/Textures/babylon.dynamicTexture.js
  83. 162 162
      src/Materials/Textures/babylon.hdrCubeTexture.js
  84. 54 54
      src/Materials/Textures/babylon.mirrorTexture.js
  85. 57 57
      src/Materials/Textures/babylon.rawTexture.js
  86. 52 52
      src/Materials/Textures/babylon.refractionTexture.js
  87. 254 254
      src/Materials/Textures/babylon.renderTargetTexture.js
  88. 274 274
      src/Materials/Textures/babylon.texture.js
  89. 58 58
      src/Materials/Textures/babylon.videoTexture.js
  90. 453 453
      src/Materials/babylon.effect.js
  91. 37 37
      src/Materials/babylon.fresnelParameters.js
  92. 318 318
      src/Materials/babylon.material.js
  93. 204 204
      src/Materials/babylon.materialHelper.js
  94. 68 68
      src/Materials/babylon.multiMaterial.js
  95. 342 342
      src/Materials/babylon.shaderMaterial.js
  96. 856 856
      src/Materials/babylon.standardMaterial.js
  97. 269 269
      src/Math/babylon.math.SIMD.js
  98. 2856 2856
      src/Math/babylon.math.js
  99. 966 966
      src/Mesh/babylon.abstractMesh.js
  100. 0 0
      src/Mesh/babylon.csg.js

+ 9 - 10
Tools/Gulp/config.json

@@ -41,7 +41,15 @@
       "../../src/Lights/Shadows/babylon.shadowGenerator.js",
       "../../src/Collisions/babylon.collider.js",
       "../../src/Collisions/babylon.collisionCoordinator.js",
+
       "../../src/Cameras/babylon.camera.js",
+      "../../src/cameras/babylon.camerainputsmanager.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.mouse.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.keyboard.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.touch.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.deviceorientation.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.gamepad.js",
+      "../../src/cameras/inputs/babylon.freecamera.input.virtualjoystick.js",
       "../../src/Cameras/babylon.targetCamera.js",
       "../../src/Cameras/babylon.freeCamera.js",
       "../../src/Cameras/babylon.followCamera.js",
@@ -193,16 +201,7 @@
       "../../src/tools/hdr/babylon.tools.hdr.js",
       "../../src/tools/hdr/babylon.tools.pmremGenerator.js",
       "../../src/materials/textures/babylon.hdrcubetexture.js",
-      "../../src/debug/babylon.skeletonViewer.js",
-
-      "../../src/cameras/composable/babylon.camerainputsmanager.js",
-      "../../src/cameras/composable/babylon.composablecamera.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.mouse.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.keyboard.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.touch.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.deviceorientation.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.gamepad.js",
-      "../../src/cameras/composable/inputs/babylon.camerainput.virtualjoystick.js"
+      "../../src/debug/babylon.skeletonViewer.js"      
     ]
   }
 }

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 30 - 21
dist/preview release/babylon.core.js


+ 175 - 73
dist/preview release/babylon.d.ts

@@ -1890,21 +1890,36 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
+    interface ICameraInput<TCamera extends BABYLON.Camera> {
+        camera: TCamera;
+        attachCamera(camera: TCamera): any;
+        detach(): any;
+        getTypeName(): string;
+        attachElement?: (element: HTMLElement, noPreventDefault?: boolean) => void;
+        detachElement?: (element: HTMLElement) => void;
+        checkInputs?: () => void;
+    }
+    interface CameraInputsMap<TCamera extends BABYLON.Camera> {
+        [name: string]: ICameraInput<TCamera>;
+        [idx: number]: ICameraInput<TCamera>;
+    }
+    class CameraInputsManager<TCamera extends BABYLON.Camera> {
+        inputs: CameraInputsMap<TCamera>;
+        camera: TCamera;
+        checkInputs: () => void;
+        constructor(camera: TCamera);
+        add(input: ICameraInput<TCamera>): void;
+        private _addCheckInputs(fn);
+        attachElement(element: HTMLElement, noPreventDefault?: boolean): void;
+        detachElement(element: HTMLElement): void;
+        rebuildInputCheck(element: HTMLElement): void;
+        clear(): void;
+    }
+}
+
+declare module BABYLON {
     class DeviceOrientationCamera extends FreeCamera {
-        private _offsetX;
-        private _offsetY;
-        private _orientationGamma;
-        private _orientationBeta;
-        private _initialOrientationGamma;
-        private _initialOrientationBeta;
-        private _attachedCanvas;
-        private _orientationChanged;
-        angularSensibility: number;
-        moveSensibility: number;
         constructor(name: string, position: Vector3, scene: Scene);
-        attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void;
-        detachControl(canvas: HTMLCanvasElement): void;
-        _checkInputs(): void;
         getTypeName(): string;
     }
 }
@@ -1939,31 +1954,20 @@ declare module BABYLON {
 declare module BABYLON {
     class FreeCamera extends TargetCamera {
         ellipsoid: Vector3;
-        keysUp: number[];
-        keysDown: number[];
-        keysLeft: number[];
-        keysRight: number[];
         checkCollisions: boolean;
         applyGravity: boolean;
-        angularSensibility: number;
+        inputs: FreeCameraInputsManager;
         onCollide: (collidedMesh: AbstractMesh) => void;
-        private _keys;
         private _collider;
         private _needMoveForGravity;
         private _oldPosition;
         private _diffPosition;
         private _newPosition;
-        private _attachedElement;
-        private _localDirection;
-        private _transformedDirection;
-        private _onMouseDown;
-        private _onMouseUp;
-        private _onMouseOut;
-        private _onMouseMove;
-        private _onKeyDown;
-        private _onKeyUp;
+        _attachedElement: HTMLElement;
+        _noPreventDefault: boolean;
+        _localDirection: Vector3;
+        _transformedDirection: Vector3;
         constructor(name: string, position: Vector3, scene: Scene);
-        _onLostFocus(e: FocusEvent): void;
         attachControl(element: HTMLElement, noPreventDefault?: boolean): void;
         detachControl(element: HTMLElement): void;
         _collideWithWorld(velocity: Vector3): void;
@@ -1971,8 +1975,18 @@ declare module BABYLON {
         _checkInputs(): void;
         _decideIfNeedsToMove(): boolean;
         _updatePosition(): void;
+        dispose(): void;
         getTypeName(): string;
     }
+    class FreeCameraInputsManager extends CameraInputsManager<FreeCamera> {
+        constructor(camera: FreeCamera);
+        add(input: ICameraInput<FreeCamera>): void;
+        addKeyboard(): this;
+        addMouse(): this;
+        addGamepad(): this;
+        addDeviceOrientation(): this;
+        addTouch(): this;
+    }
 }
 
 declare module BABYLON {
@@ -2067,37 +2081,14 @@ declare module BABYLON {
 
 declare module BABYLON {
     class TouchCamera extends FreeCamera {
-        private _offsetX;
-        private _offsetY;
-        private _pointerCount;
-        private _pointerPressed;
-        private _attachedCanvas;
-        private _onPointerDown;
-        private _onPointerUp;
-        private _onPointerMove;
-        touchAngularSensibility: number;
-        touchMoveSensibility: number;
         constructor(name: string, position: Vector3, scene: Scene);
-        _onLostFocus(e: FocusEvent): void;
-        attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void;
-        detachControl(canvas: HTMLCanvasElement): void;
-        _checkInputs(): void;
         getTypeName(): string;
     }
 }
 
 declare module BABYLON {
     class UniversalCamera extends TouchCamera {
-        gamepad: Gamepad;
-        private _gamepads;
-        gamepadAngularSensibility: number;
-        gamepadMoveSensibility: number;
         constructor(name: string, position: Vector3, scene: Scene);
-        private _onNewGameConnected(gamepad);
-        attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void;
-        detachControl(canvas: HTMLCanvasElement): void;
-        _checkInputs(): void;
-        dispose(): void;
         getTypeName(): string;
     }
 }
@@ -5634,27 +5625,6 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
-    class ReflectionProbe {
-        name: string;
-        private _scene;
-        private _renderTargetTexture;
-        private _projectionMatrix;
-        private _viewMatrix;
-        private _target;
-        private _add;
-        private _attachedMesh;
-        position: Vector3;
-        constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean);
-        refreshRate: number;
-        getScene(): Scene;
-        cubeTexture: RenderTargetTexture;
-        renderList: AbstractMesh[];
-        attachToMesh(mesh: AbstractMesh): void;
-        dispose(): void;
-    }
-}
-
-declare module BABYLON {
     class AnaglyphPostProcess extends PostProcess {
         constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean);
     }
@@ -6224,6 +6194,27 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
+    class ReflectionProbe {
+        name: string;
+        private _scene;
+        private _renderTargetTexture;
+        private _projectionMatrix;
+        private _viewMatrix;
+        private _target;
+        private _add;
+        private _attachedMesh;
+        position: Vector3;
+        constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean);
+        refreshRate: number;
+        getScene(): Scene;
+        cubeTexture: RenderTargetTexture;
+        renderList: AbstractMesh[];
+        attachToMesh(mesh: AbstractMesh): void;
+        dispose(): void;
+    }
+}
+
+declare module BABYLON {
     class BoundingBoxRenderer {
         frontColor: Color3;
         backColor: Color3;
@@ -7111,6 +7102,117 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
+    class FreeCameraDeviceOrientationInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        private _offsetX;
+        private _offsetY;
+        private _orientationGamma;
+        private _orientationBeta;
+        private _initialOrientationGamma;
+        private _initialOrientationBeta;
+        private _orientationChanged;
+        private _resetOrientationGamma;
+        angularSensibility: number;
+        moveSensibility: number;
+        constructor();
+        attachCamera(camera: FreeCamera): void;
+        resetOrientationGamma(): void;
+        orientationChanged(evt: any): void;
+        detach(): void;
+        checkInputs(): void;
+        getTypeName(): string;
+    }
+}
+
+declare module BABYLON {
+    class FreeCameraGamepadInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        gamepad: Gamepad;
+        private _gamepads;
+        gamepadAngularSensibility: number;
+        gamepadMoveSensibility: number;
+        constructor();
+        attachCamera(camera: FreeCamera): void;
+        detach(): void;
+        checkInputs(): void;
+        private _onNewGameConnected(gamepad);
+        getTypeName(): string;
+    }
+}
+
+declare module BABYLON {
+    class FreeCameraKeyboardMoveInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        private _keys;
+        private _onKeyDown;
+        private _onKeyUp;
+        keysUp: number[];
+        keysDown: number[];
+        keysLeft: number[];
+        keysRight: number[];
+        attachCamera(camera: FreeCamera): void;
+        detach(): void;
+        checkInputs(): void;
+        getTypeName(): string;
+        _onLostFocus(e: FocusEvent): void;
+    }
+}
+
+declare module BABYLON {
+    class FreeCameraMouseInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        attachedElement: HTMLElement;
+        angularSensibility: number;
+        private _onMouseDown;
+        private _onMouseUp;
+        private _onMouseOut;
+        private _onMouseMove;
+        attachCamera(camera: FreeCamera): void;
+        attachElement(element: HTMLElement, noPreventDefault?: boolean): void;
+        detachElement(element: HTMLElement): void;
+        detach(): void;
+        getTypeName(): string;
+    }
+}
+
+declare module BABYLON {
+    class FreeCameraTouchInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        private _offsetX;
+        private _offsetY;
+        private _pointerCount;
+        private _pointerPressed;
+        private _attachedElement;
+        private _onPointerDown;
+        private _onPointerUp;
+        private _onPointerMove;
+        private _onLostFocus;
+        touchAngularSensibility: number;
+        touchMoveSensibility: number;
+        attachCamera(camera: FreeCamera): void;
+        attachElement(element: HTMLElement, noPreventDefault?: boolean): void;
+        detachElement(element: HTMLElement): void;
+        checkInputs(): void;
+        detach(): void;
+        getTypeName(): string;
+    }
+}
+
+declare module BABYLON {
+    class FreeCameraVirtualJoystickInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
+        private _leftjoystick;
+        private _rightjoystick;
+        getLeftJoystick(): VirtualJoystick;
+        getRightJoystick(): VirtualJoystick;
+        checkInputs(): void;
+        attachCamera(camera: FreeCamera): void;
+        detach(): void;
+        getTypeName(): string;
+    }
+}
+
+declare module BABYLON {
     class VRCameraMetrics {
         hResolution: number;
         vResolution: number;

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 35 - 29
dist/preview release/babylon.js


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 27907 - 28114
dist/preview release/babylon.max.js


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 39 - 28
dist/preview release/babylon.noworker.js


+ 72 - 72
src/Actions/babylon.action.js

@@ -1,72 +1,72 @@
-var BABYLON;
-(function (BABYLON) {
-    var Action = (function () {
-        function Action(triggerOptions, condition) {
-            this.triggerOptions = triggerOptions;
-            if (triggerOptions.parameter) {
-                this.trigger = triggerOptions.trigger;
-                this._triggerParameter = triggerOptions.parameter;
-            }
-            else {
-                this.trigger = triggerOptions;
-            }
-            this._nextActiveAction = this;
-            this._condition = condition;
-        }
-        // Methods
-        Action.prototype._prepare = function () {
-        };
-        Action.prototype.getTriggerParameter = function () {
-            return this._triggerParameter;
-        };
-        Action.prototype._executeCurrent = function (evt) {
-            if (this._nextActiveAction._condition) {
-                var condition = this._nextActiveAction._condition;
-                var currentRenderId = this._actionManager.getScene().getRenderId();
-                // We cache the current evaluation for the current frame
-                if (condition._evaluationId === currentRenderId) {
-                    if (!condition._currentResult) {
-                        return;
-                    }
-                }
-                else {
-                    condition._evaluationId = currentRenderId;
-                    if (!condition.isValid()) {
-                        condition._currentResult = false;
-                        return;
-                    }
-                    condition._currentResult = true;
-                }
-            }
-            this._nextActiveAction.execute(evt);
-            this.skipToNextActiveAction();
-        };
-        Action.prototype.execute = function (evt) {
-        };
-        Action.prototype.skipToNextActiveAction = function () {
-            if (this._nextActiveAction._child) {
-                if (!this._nextActiveAction._child._actionManager) {
-                    this._nextActiveAction._child._actionManager = this._actionManager;
-                }
-                this._nextActiveAction = this._nextActiveAction._child;
-            }
-            else {
-                this._nextActiveAction = this;
-            }
-        };
-        Action.prototype.then = function (action) {
-            this._child = action;
-            action._actionManager = this._actionManager;
-            action._prepare();
-            return action;
-        };
-        Action.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        return Action;
-    })();
-    BABYLON.Action = Action;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Action = (function () {
+        function Action(triggerOptions, condition) {
+            this.triggerOptions = triggerOptions;
+            if (triggerOptions.parameter) {
+                this.trigger = triggerOptions.trigger;
+                this._triggerParameter = triggerOptions.parameter;
+            }
+            else {
+                this.trigger = triggerOptions;
+            }
+            this._nextActiveAction = this;
+            this._condition = condition;
+        }
+        // Methods
+        Action.prototype._prepare = function () {
+        };
+        Action.prototype.getTriggerParameter = function () {
+            return this._triggerParameter;
+        };
+        Action.prototype._executeCurrent = function (evt) {
+            if (this._nextActiveAction._condition) {
+                var condition = this._nextActiveAction._condition;
+                var currentRenderId = this._actionManager.getScene().getRenderId();
+                // We cache the current evaluation for the current frame
+                if (condition._evaluationId === currentRenderId) {
+                    if (!condition._currentResult) {
+                        return;
+                    }
+                }
+                else {
+                    condition._evaluationId = currentRenderId;
+                    if (!condition.isValid()) {
+                        condition._currentResult = false;
+                        return;
+                    }
+                    condition._currentResult = true;
+                }
+            }
+            this._nextActiveAction.execute(evt);
+            this.skipToNextActiveAction();
+        };
+        Action.prototype.execute = function (evt) {
+        };
+        Action.prototype.skipToNextActiveAction = function () {
+            if (this._nextActiveAction._child) {
+                if (!this._nextActiveAction._child._actionManager) {
+                    this._nextActiveAction._child._actionManager = this._actionManager;
+                }
+                this._nextActiveAction = this._nextActiveAction._child;
+            }
+            else {
+                this._nextActiveAction = this;
+            }
+        };
+        Action.prototype.then = function (action) {
+            this._child = action;
+            action._actionManager = this._actionManager;
+            action._prepare();
+            return action;
+        };
+        Action.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        return Action;
+    }());
+    BABYLON.Action = Action;
+})(BABYLON || (BABYLON = {}));

+ 473 - 473
src/Actions/babylon.actionManager.js

@@ -1,473 +1,473 @@
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * ActionEvent is the event beint sent when an action is triggered.
-     */
-    var ActionEvent = (function () {
-        /**
-         * @constructor
-         * @param source The mesh or sprite that triggered the action.
-         * @param pointerX The X mouse cursor position at the time of the event
-         * @param pointerY The Y mouse cursor position at the time of the event
-         * @param meshUnderPointer The mesh that is currently pointed at (can be null)
-         * @param sourceEvent the original (browser) event that triggered the ActionEvent
-         */
-        function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
-            this.source = source;
-            this.pointerX = pointerX;
-            this.pointerY = pointerY;
-            this.meshUnderPointer = meshUnderPointer;
-            this.sourceEvent = sourceEvent;
-            this.additionalData = additionalData;
-        }
-        /**
-         * Helper function to auto-create an ActionEvent from a source mesh.
-         * @param source The source mesh that triggered the event
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNew = function (source, evt, additionalData) {
-            var scene = source.getScene();
-            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
-        };
-        /**
-         * Helper function to auto-create an ActionEvent from a source mesh.
-         * @param source The source sprite that triggered the event
-         * @param scene Scene associated with the sprite
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
-            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
-        };
-        /**
-         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
-         * @param scene the scene where the event occurred
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNewFromScene = function (scene, evt) {
-            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
-        };
-        return ActionEvent;
-    })();
-    BABYLON.ActionEvent = ActionEvent;
-    /**
-     * Action Manager manages all events to be triggered on a given mesh or the global scene.
-     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
-     */
-    var ActionManager = (function () {
-        function ActionManager(scene) {
-            // Members
-            this.actions = new Array();
-            this._scene = scene;
-            scene._actionManagers.push(this);
-        }
-        Object.defineProperty(ActionManager, "NothingTrigger", {
-            get: function () {
-                return ActionManager._NothingTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickTrigger", {
-            get: function () {
-                return ActionManager._OnPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
-            get: function () {
-                return ActionManager._OnLeftPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnRightPickTrigger", {
-            get: function () {
-                return ActionManager._OnRightPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
-            get: function () {
-                return ActionManager._OnCenterPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickDownTrigger", {
-            get: function () {
-                return ActionManager._OnPickDownTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickUpTrigger", {
-            get: function () {
-                return ActionManager._OnPickUpTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickOutTrigger", {
-            /// This trigger will only be raised if you also declared a OnPickDown
-            get: function () {
-                return ActionManager._OnPickOutTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnLongPressTrigger", {
-            get: function () {
-                return ActionManager._OnLongPressTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
-            get: function () {
-                return ActionManager._OnPointerOverTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
-            get: function () {
-                return ActionManager._OnPointerOutTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
-            get: function () {
-                return ActionManager._OnEveryFrameTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
-            get: function () {
-                return ActionManager._OnIntersectionEnterTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
-            get: function () {
-                return ActionManager._OnIntersectionExitTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
-            get: function () {
-                return ActionManager._OnKeyDownTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
-            get: function () {
-                return ActionManager._OnKeyUpTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        ActionManager.prototype.dispose = function () {
-            var index = this._scene._actionManagers.indexOf(this);
-            if (index > -1) {
-                this._scene._actionManagers.splice(index, 1);
-            }
-        };
-        ActionManager.prototype.getScene = function () {
-            return this._scene;
-        };
-        /**
-         * Does this action manager handles actions of any of the given triggers
-         * @param {number[]} triggers - the triggers to be tested
-         * @return {boolean} whether one (or more) of the triggers is handeled
-         */
-        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (triggers.indexOf(action.trigger) > -1) {
-                    return true;
-                }
-            }
-            return false;
-        };
-        /**
-         * Does this action manager handles actions of a given trigger
-         * @param {number} trigger - the trigger to be tested
-         * @return {boolean} whether the trigger is handeled
-         */
-        ActionManager.prototype.hasSpecificTrigger = function (trigger) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (action.trigger === trigger) {
-                    return true;
-                }
-            }
-            return false;
-        };
-        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
-            /**
-             * Does this action manager has pointer triggers
-             * @return {boolean} whether or not it has pointer triggers
-             */
-            get: function () {
-                for (var index = 0; index < this.actions.length; index++) {
-                    var action = this.actions[index];
-                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
-                        return true;
-                    }
-                }
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
-            /**
-             * Does this action manager has pick triggers
-             * @return {boolean} whether or not it has pick triggers
-             */
-            get: function () {
-                for (var index = 0; index < this.actions.length; index++) {
-                    var action = this.actions[index];
-                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
-                        return true;
-                    }
-                }
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Registers an action to this action manager
-         * @param {BABYLON.Action} action - the action to be registered
-         * @return {BABYLON.Action} the action amended (prepared) after registration
-         */
-        ActionManager.prototype.registerAction = function (action) {
-            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
-                if (this.getScene().actionManager !== this) {
-                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
-                    return null;
-                }
-            }
-            this.actions.push(action);
-            action._actionManager = this;
-            action._prepare();
-            return action;
-        };
-        /**
-         * Process a specific trigger
-         * @param {number} trigger - the trigger to process
-         * @param evt {BABYLON.ActionEvent} the event details to be processed
-         */
-        ActionManager.prototype.processTrigger = function (trigger, evt) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (action.trigger === trigger) {
-                    if (trigger === ActionManager.OnKeyUpTrigger
-                        || trigger === ActionManager.OnKeyDownTrigger) {
-                        var parameter = action.getTriggerParameter();
-                        if (parameter) {
-                            var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
-                            var actualkey = String.fromCharCode(unicode).toLowerCase();
-                            if (actualkey !== parameter.toLowerCase()) {
-                                continue;
-                            }
-                        }
-                    }
-                    action._executeCurrent(evt);
-                }
-            }
-        };
-        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
-            var properties = propertyPath.split(".");
-            for (var index = 0; index < properties.length - 1; index++) {
-                target = target[properties[index]];
-            }
-            return target;
-        };
-        ActionManager.prototype._getProperty = function (propertyPath) {
-            var properties = propertyPath.split(".");
-            return properties[properties.length - 1];
-        };
-        ActionManager.Parse = function (parsedActions, object, scene) {
-            var actionManager = new BABYLON.ActionManager(scene);
-            if (object === null)
-                scene.actionManager = actionManager;
-            else
-                object.actionManager = actionManager;
-            // instanciate a new object
-            var instanciate = function (name, params) {
-                var newInstance = Object.create(BABYLON[name].prototype);
-                newInstance.constructor.apply(newInstance, params);
-                return newInstance;
-            };
-            var parseParameter = function (name, value, target, propertyPath) {
-                if (propertyPath === null) {
-                    // String, boolean or float
-                    var floatValue = parseFloat(value);
-                    if (value === "true" || value === "false")
-                        return value === "true";
-                    else
-                        return isNaN(floatValue) ? value : floatValue;
-                }
-                var effectiveTarget = propertyPath.split(".");
-                var values = value.split(",");
-                // Get effective Target
-                for (var i = 0; i < effectiveTarget.length; i++) {
-                    target = target[effectiveTarget[i]];
-                }
-                // Return appropriate value with its type
-                if (typeof (target) === "boolean")
-                    return values[0] === "true";
-                if (typeof (target) === "string")
-                    return values[0];
-                // Parameters with multiple values such as Vector3 etc.
-                var split = new Array();
-                for (var i = 0; i < values.length; i++)
-                    split.push(parseFloat(values[i]));
-                if (target instanceof BABYLON.Vector3)
-                    return BABYLON.Vector3.FromArray(split);
-                if (target instanceof BABYLON.Vector4)
-                    return BABYLON.Vector4.FromArray(split);
-                if (target instanceof BABYLON.Color3)
-                    return BABYLON.Color3.FromArray(split);
-                if (target instanceof BABYLON.Color4)
-                    return BABYLON.Color4.FromArray(split);
-                return parseFloat(values[0]);
-            };
-            // traverse graph per trigger
-            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
-                if (combineArray === void 0) { combineArray = null; }
-                if (parsedAction.detached)
-                    return;
-                var parameters = new Array();
-                var target = null;
-                var propertyPath = null;
-                var combine = parsedAction.combine && parsedAction.combine.length > 0;
-                // Parameters
-                if (parsedAction.type === 2)
-                    parameters.push(actionManager);
-                else
-                    parameters.push(trigger);
-                if (combine) {
-                    var actions = new Array();
-                    for (var j = 0; j < parsedAction.combine.length; j++) {
-                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
-                    }
-                    parameters.push(actions);
-                }
-                else {
-                    for (var i = 0; i < parsedAction.properties.length; i++) {
-                        var value = parsedAction.properties[i].value;
-                        var name = parsedAction.properties[i].name;
-                        var targetType = parsedAction.properties[i].targetType;
-                        if (name === "target")
-                            if (targetType !== null && targetType === "SceneProperties")
-                                value = target = scene;
-                            else
-                                value = target = scene.getNodeByName(value);
-                        else if (name === "parent")
-                            value = scene.getNodeByName(value);
-                        else if (name === "sound")
-                            value = scene.getSoundByName(value);
-                        else if (name !== "propertyPath") {
-                            if (parsedAction.type === 2 && name === "operator")
-                                value = BABYLON.ValueCondition[value];
-                            else
-                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
-                        }
-                        else {
-                            propertyPath = value;
-                        }
-                        parameters.push(value);
-                    }
-                }
-                if (combineArray === null) {
-                    parameters.push(condition);
-                }
-                else {
-                    parameters.push(null);
-                }
-                // If interpolate value action
-                if (parsedAction.name === "InterpolateValueAction") {
-                    var param = parameters[parameters.length - 2];
-                    parameters[parameters.length - 1] = param;
-                    parameters[parameters.length - 2] = condition;
-                }
-                // Action or condition(s) and not CombineAction
-                var newAction = instanciate(parsedAction.name, parameters);
-                if (newAction instanceof BABYLON.Condition && condition !== null) {
-                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
-                    if (action)
-                        action.then(nothing);
-                    else
-                        actionManager.registerAction(nothing);
-                    action = nothing;
-                }
-                if (combineArray === null) {
-                    if (newAction instanceof BABYLON.Condition) {
-                        condition = newAction;
-                        newAction = action;
-                    }
-                    else {
-                        condition = null;
-                        if (action)
-                            action.then(newAction);
-                        else
-                            actionManager.registerAction(newAction);
-                    }
-                }
-                else {
-                    combineArray.push(newAction);
-                }
-                for (var i = 0; i < parsedAction.children.length; i++)
-                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
-            };
-            // triggers
-            for (var i = 0; i < parsedActions.children.length; i++) {
-                var triggerParams;
-                var trigger = parsedActions.children[i];
-                if (trigger.properties.length > 0) {
-                    var param = trigger.properties[0].value;
-                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
-                    triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
-                }
-                else
-                    triggerParams = BABYLON.ActionManager[trigger.name];
-                for (var j = 0; j < trigger.children.length; j++) {
-                    if (!trigger.detached)
-                        traverse(trigger.children[j], triggerParams, null, null);
-                }
-            }
-        };
-        // Statics
-        ActionManager._NothingTrigger = 0;
-        ActionManager._OnPickTrigger = 1;
-        ActionManager._OnLeftPickTrigger = 2;
-        ActionManager._OnRightPickTrigger = 3;
-        ActionManager._OnCenterPickTrigger = 4;
-        ActionManager._OnPickDownTrigger = 5;
-        ActionManager._OnPickUpTrigger = 6;
-        ActionManager._OnLongPressTrigger = 7;
-        ActionManager._OnPointerOverTrigger = 8;
-        ActionManager._OnPointerOutTrigger = 9;
-        ActionManager._OnEveryFrameTrigger = 10;
-        ActionManager._OnIntersectionEnterTrigger = 11;
-        ActionManager._OnIntersectionExitTrigger = 12;
-        ActionManager._OnKeyDownTrigger = 13;
-        ActionManager._OnKeyUpTrigger = 14;
-        ActionManager._OnPickOutTrigger = 15;
-        ActionManager.DragMovementThreshold = 10; // in pixels
-        ActionManager.LongPressDelay = 500; // in milliseconds
-        return ActionManager;
-    })();
-    BABYLON.ActionManager = ActionManager;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * ActionEvent is the event beint sent when an action is triggered.
+     */
+    var ActionEvent = (function () {
+        /**
+         * @constructor
+         * @param source The mesh or sprite that triggered the action.
+         * @param pointerX The X mouse cursor position at the time of the event
+         * @param pointerY The Y mouse cursor position at the time of the event
+         * @param meshUnderPointer The mesh that is currently pointed at (can be null)
+         * @param sourceEvent the original (browser) event that triggered the ActionEvent
+         */
+        function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
+            this.source = source;
+            this.pointerX = pointerX;
+            this.pointerY = pointerY;
+            this.meshUnderPointer = meshUnderPointer;
+            this.sourceEvent = sourceEvent;
+            this.additionalData = additionalData;
+        }
+        /**
+         * Helper function to auto-create an ActionEvent from a source mesh.
+         * @param source The source mesh that triggered the event
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNew = function (source, evt, additionalData) {
+            var scene = source.getScene();
+            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
+        };
+        /**
+         * Helper function to auto-create an ActionEvent from a source mesh.
+         * @param source The source sprite that triggered the event
+         * @param scene Scene associated with the sprite
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
+            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
+        };
+        /**
+         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
+         * @param scene the scene where the event occurred
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNewFromScene = function (scene, evt) {
+            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
+        };
+        return ActionEvent;
+    }());
+    BABYLON.ActionEvent = ActionEvent;
+    /**
+     * Action Manager manages all events to be triggered on a given mesh or the global scene.
+     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
+     */
+    var ActionManager = (function () {
+        function ActionManager(scene) {
+            // Members
+            this.actions = new Array();
+            this._scene = scene;
+            scene._actionManagers.push(this);
+        }
+        Object.defineProperty(ActionManager, "NothingTrigger", {
+            get: function () {
+                return ActionManager._NothingTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickTrigger", {
+            get: function () {
+                return ActionManager._OnPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
+            get: function () {
+                return ActionManager._OnLeftPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnRightPickTrigger", {
+            get: function () {
+                return ActionManager._OnRightPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
+            get: function () {
+                return ActionManager._OnCenterPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickDownTrigger", {
+            get: function () {
+                return ActionManager._OnPickDownTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickUpTrigger", {
+            get: function () {
+                return ActionManager._OnPickUpTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickOutTrigger", {
+            /// This trigger will only be raised if you also declared a OnPickDown
+            get: function () {
+                return ActionManager._OnPickOutTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnLongPressTrigger", {
+            get: function () {
+                return ActionManager._OnLongPressTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
+            get: function () {
+                return ActionManager._OnPointerOverTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
+            get: function () {
+                return ActionManager._OnPointerOutTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
+            get: function () {
+                return ActionManager._OnEveryFrameTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
+            get: function () {
+                return ActionManager._OnIntersectionEnterTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
+            get: function () {
+                return ActionManager._OnIntersectionExitTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
+            get: function () {
+                return ActionManager._OnKeyDownTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
+            get: function () {
+                return ActionManager._OnKeyUpTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        ActionManager.prototype.dispose = function () {
+            var index = this._scene._actionManagers.indexOf(this);
+            if (index > -1) {
+                this._scene._actionManagers.splice(index, 1);
+            }
+        };
+        ActionManager.prototype.getScene = function () {
+            return this._scene;
+        };
+        /**
+         * Does this action manager handles actions of any of the given triggers
+         * @param {number[]} triggers - the triggers to be tested
+         * @return {boolean} whether one (or more) of the triggers is handeled
+         */
+        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (triggers.indexOf(action.trigger) > -1) {
+                    return true;
+                }
+            }
+            return false;
+        };
+        /**
+         * Does this action manager handles actions of a given trigger
+         * @param {number} trigger - the trigger to be tested
+         * @return {boolean} whether the trigger is handeled
+         */
+        ActionManager.prototype.hasSpecificTrigger = function (trigger) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (action.trigger === trigger) {
+                    return true;
+                }
+            }
+            return false;
+        };
+        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
+            /**
+             * Does this action manager has pointer triggers
+             * @return {boolean} whether or not it has pointer triggers
+             */
+            get: function () {
+                for (var index = 0; index < this.actions.length; index++) {
+                    var action = this.actions[index];
+                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
+                        return true;
+                    }
+                }
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
+            /**
+             * Does this action manager has pick triggers
+             * @return {boolean} whether or not it has pick triggers
+             */
+            get: function () {
+                for (var index = 0; index < this.actions.length; index++) {
+                    var action = this.actions[index];
+                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
+                        return true;
+                    }
+                }
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Registers an action to this action manager
+         * @param {BABYLON.Action} action - the action to be registered
+         * @return {BABYLON.Action} the action amended (prepared) after registration
+         */
+        ActionManager.prototype.registerAction = function (action) {
+            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
+                if (this.getScene().actionManager !== this) {
+                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
+                    return null;
+                }
+            }
+            this.actions.push(action);
+            action._actionManager = this;
+            action._prepare();
+            return action;
+        };
+        /**
+         * Process a specific trigger
+         * @param {number} trigger - the trigger to process
+         * @param evt {BABYLON.ActionEvent} the event details to be processed
+         */
+        ActionManager.prototype.processTrigger = function (trigger, evt) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (action.trigger === trigger) {
+                    if (trigger === ActionManager.OnKeyUpTrigger
+                        || trigger === ActionManager.OnKeyDownTrigger) {
+                        var parameter = action.getTriggerParameter();
+                        if (parameter) {
+                            var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
+                            var actualkey = String.fromCharCode(unicode).toLowerCase();
+                            if (actualkey !== parameter.toLowerCase()) {
+                                continue;
+                            }
+                        }
+                    }
+                    action._executeCurrent(evt);
+                }
+            }
+        };
+        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
+            var properties = propertyPath.split(".");
+            for (var index = 0; index < properties.length - 1; index++) {
+                target = target[properties[index]];
+            }
+            return target;
+        };
+        ActionManager.prototype._getProperty = function (propertyPath) {
+            var properties = propertyPath.split(".");
+            return properties[properties.length - 1];
+        };
+        ActionManager.Parse = function (parsedActions, object, scene) {
+            var actionManager = new BABYLON.ActionManager(scene);
+            if (object === null)
+                scene.actionManager = actionManager;
+            else
+                object.actionManager = actionManager;
+            // instanciate a new object
+            var instanciate = function (name, params) {
+                var newInstance = Object.create(BABYLON[name].prototype);
+                newInstance.constructor.apply(newInstance, params);
+                return newInstance;
+            };
+            var parseParameter = function (name, value, target, propertyPath) {
+                if (propertyPath === null) {
+                    // String, boolean or float
+                    var floatValue = parseFloat(value);
+                    if (value === "true" || value === "false")
+                        return value === "true";
+                    else
+                        return isNaN(floatValue) ? value : floatValue;
+                }
+                var effectiveTarget = propertyPath.split(".");
+                var values = value.split(",");
+                // Get effective Target
+                for (var i = 0; i < effectiveTarget.length; i++) {
+                    target = target[effectiveTarget[i]];
+                }
+                // Return appropriate value with its type
+                if (typeof (target) === "boolean")
+                    return values[0] === "true";
+                if (typeof (target) === "string")
+                    return values[0];
+                // Parameters with multiple values such as Vector3 etc.
+                var split = new Array();
+                for (var i = 0; i < values.length; i++)
+                    split.push(parseFloat(values[i]));
+                if (target instanceof BABYLON.Vector3)
+                    return BABYLON.Vector3.FromArray(split);
+                if (target instanceof BABYLON.Vector4)
+                    return BABYLON.Vector4.FromArray(split);
+                if (target instanceof BABYLON.Color3)
+                    return BABYLON.Color3.FromArray(split);
+                if (target instanceof BABYLON.Color4)
+                    return BABYLON.Color4.FromArray(split);
+                return parseFloat(values[0]);
+            };
+            // traverse graph per trigger
+            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
+                if (combineArray === void 0) { combineArray = null; }
+                if (parsedAction.detached)
+                    return;
+                var parameters = new Array();
+                var target = null;
+                var propertyPath = null;
+                var combine = parsedAction.combine && parsedAction.combine.length > 0;
+                // Parameters
+                if (parsedAction.type === 2)
+                    parameters.push(actionManager);
+                else
+                    parameters.push(trigger);
+                if (combine) {
+                    var actions = new Array();
+                    for (var j = 0; j < parsedAction.combine.length; j++) {
+                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
+                    }
+                    parameters.push(actions);
+                }
+                else {
+                    for (var i = 0; i < parsedAction.properties.length; i++) {
+                        var value = parsedAction.properties[i].value;
+                        var name = parsedAction.properties[i].name;
+                        var targetType = parsedAction.properties[i].targetType;
+                        if (name === "target")
+                            if (targetType !== null && targetType === "SceneProperties")
+                                value = target = scene;
+                            else
+                                value = target = scene.getNodeByName(value);
+                        else if (name === "parent")
+                            value = scene.getNodeByName(value);
+                        else if (name === "sound")
+                            value = scene.getSoundByName(value);
+                        else if (name !== "propertyPath") {
+                            if (parsedAction.type === 2 && name === "operator")
+                                value = BABYLON.ValueCondition[value];
+                            else
+                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
+                        }
+                        else {
+                            propertyPath = value;
+                        }
+                        parameters.push(value);
+                    }
+                }
+                if (combineArray === null) {
+                    parameters.push(condition);
+                }
+                else {
+                    parameters.push(null);
+                }
+                // If interpolate value action
+                if (parsedAction.name === "InterpolateValueAction") {
+                    var param = parameters[parameters.length - 2];
+                    parameters[parameters.length - 1] = param;
+                    parameters[parameters.length - 2] = condition;
+                }
+                // Action or condition(s) and not CombineAction
+                var newAction = instanciate(parsedAction.name, parameters);
+                if (newAction instanceof BABYLON.Condition && condition !== null) {
+                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
+                    if (action)
+                        action.then(nothing);
+                    else
+                        actionManager.registerAction(nothing);
+                    action = nothing;
+                }
+                if (combineArray === null) {
+                    if (newAction instanceof BABYLON.Condition) {
+                        condition = newAction;
+                        newAction = action;
+                    }
+                    else {
+                        condition = null;
+                        if (action)
+                            action.then(newAction);
+                        else
+                            actionManager.registerAction(newAction);
+                    }
+                }
+                else {
+                    combineArray.push(newAction);
+                }
+                for (var i = 0; i < parsedAction.children.length; i++)
+                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
+            };
+            // triggers
+            for (var i = 0; i < parsedActions.children.length; i++) {
+                var triggerParams;
+                var trigger = parsedActions.children[i];
+                if (trigger.properties.length > 0) {
+                    var param = trigger.properties[0].value;
+                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
+                    triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
+                }
+                else
+                    triggerParams = BABYLON.ActionManager[trigger.name];
+                for (var j = 0; j < trigger.children.length; j++) {
+                    if (!trigger.detached)
+                        traverse(trigger.children[j], triggerParams, null, null);
+                }
+            }
+        };
+        // Statics
+        ActionManager._NothingTrigger = 0;
+        ActionManager._OnPickTrigger = 1;
+        ActionManager._OnLeftPickTrigger = 2;
+        ActionManager._OnRightPickTrigger = 3;
+        ActionManager._OnCenterPickTrigger = 4;
+        ActionManager._OnPickDownTrigger = 5;
+        ActionManager._OnPickUpTrigger = 6;
+        ActionManager._OnLongPressTrigger = 7;
+        ActionManager._OnPointerOverTrigger = 8;
+        ActionManager._OnPointerOutTrigger = 9;
+        ActionManager._OnEveryFrameTrigger = 10;
+        ActionManager._OnIntersectionEnterTrigger = 11;
+        ActionManager._OnIntersectionExitTrigger = 12;
+        ActionManager._OnKeyDownTrigger = 13;
+        ActionManager._OnKeyUpTrigger = 14;
+        ActionManager._OnPickOutTrigger = 15;
+        ActionManager.DragMovementThreshold = 10; // in pixels
+        ActionManager.LongPressDelay = 500; // in milliseconds
+        return ActionManager;
+    }());
+    BABYLON.ActionManager = ActionManager;
+})(BABYLON || (BABYLON = {}));

+ 117 - 117
src/Actions/babylon.condition.js

@@ -1,117 +1,117 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Condition = (function () {
-        function Condition(actionManager) {
-            this._actionManager = actionManager;
-        }
-        Condition.prototype.isValid = function () {
-            return true;
-        };
-        Condition.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        return Condition;
-    })();
-    BABYLON.Condition = Condition;
-    var ValueCondition = (function (_super) {
-        __extends(ValueCondition, _super);
-        function ValueCondition(actionManager, target, propertyPath, value, operator) {
-            if (operator === void 0) { operator = ValueCondition.IsEqual; }
-            _super.call(this, actionManager);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this.operator = operator;
-            this._target = this._getEffectiveTarget(target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        }
-        Object.defineProperty(ValueCondition, "IsEqual", {
-            get: function () {
-                return ValueCondition._IsEqual;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsDifferent", {
-            get: function () {
-                return ValueCondition._IsDifferent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsGreater", {
-            get: function () {
-                return ValueCondition._IsGreater;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsLesser", {
-            get: function () {
-                return ValueCondition._IsLesser;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        ValueCondition.prototype.isValid = function () {
-            switch (this.operator) {
-                case ValueCondition.IsGreater:
-                    return this._target[this._property] > this.value;
-                case ValueCondition.IsLesser:
-                    return this._target[this._property] < this.value;
-                case ValueCondition.IsEqual:
-                case ValueCondition.IsDifferent:
-                    var check;
-                    if (this.value.equals) {
-                        check = this.value.equals(this._target[this._property]);
-                    }
-                    else {
-                        check = this.value === this._target[this._property];
-                    }
-                    return this.operator === ValueCondition.IsEqual ? check : !check;
-            }
-            return false;
-        };
-        // Statics
-        ValueCondition._IsEqual = 0;
-        ValueCondition._IsDifferent = 1;
-        ValueCondition._IsGreater = 2;
-        ValueCondition._IsLesser = 3;
-        return ValueCondition;
-    })(Condition);
-    BABYLON.ValueCondition = ValueCondition;
-    var PredicateCondition = (function (_super) {
-        __extends(PredicateCondition, _super);
-        function PredicateCondition(actionManager, predicate) {
-            _super.call(this, actionManager);
-            this.predicate = predicate;
-        }
-        PredicateCondition.prototype.isValid = function () {
-            return this.predicate();
-        };
-        return PredicateCondition;
-    })(Condition);
-    BABYLON.PredicateCondition = PredicateCondition;
-    var StateCondition = (function (_super) {
-        __extends(StateCondition, _super);
-        function StateCondition(actionManager, target, value) {
-            _super.call(this, actionManager);
-            this.value = value;
-            this._target = target;
-        }
-        // Methods
-        StateCondition.prototype.isValid = function () {
-            return this._target.state === this.value;
-        };
-        return StateCondition;
-    })(Condition);
-    BABYLON.StateCondition = StateCondition;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Condition = (function () {
+        function Condition(actionManager) {
+            this._actionManager = actionManager;
+        }
+        Condition.prototype.isValid = function () {
+            return true;
+        };
+        Condition.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        return Condition;
+    }());
+    BABYLON.Condition = Condition;
+    var ValueCondition = (function (_super) {
+        __extends(ValueCondition, _super);
+        function ValueCondition(actionManager, target, propertyPath, value, operator) {
+            if (operator === void 0) { operator = ValueCondition.IsEqual; }
+            _super.call(this, actionManager);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this.operator = operator;
+            this._target = this._getEffectiveTarget(target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        }
+        Object.defineProperty(ValueCondition, "IsEqual", {
+            get: function () {
+                return ValueCondition._IsEqual;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsDifferent", {
+            get: function () {
+                return ValueCondition._IsDifferent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsGreater", {
+            get: function () {
+                return ValueCondition._IsGreater;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsLesser", {
+            get: function () {
+                return ValueCondition._IsLesser;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        ValueCondition.prototype.isValid = function () {
+            switch (this.operator) {
+                case ValueCondition.IsGreater:
+                    return this._target[this._property] > this.value;
+                case ValueCondition.IsLesser:
+                    return this._target[this._property] < this.value;
+                case ValueCondition.IsEqual:
+                case ValueCondition.IsDifferent:
+                    var check;
+                    if (this.value.equals) {
+                        check = this.value.equals(this._target[this._property]);
+                    }
+                    else {
+                        check = this.value === this._target[this._property];
+                    }
+                    return this.operator === ValueCondition.IsEqual ? check : !check;
+            }
+            return false;
+        };
+        // Statics
+        ValueCondition._IsEqual = 0;
+        ValueCondition._IsDifferent = 1;
+        ValueCondition._IsGreater = 2;
+        ValueCondition._IsLesser = 3;
+        return ValueCondition;
+    }(Condition));
+    BABYLON.ValueCondition = ValueCondition;
+    var PredicateCondition = (function (_super) {
+        __extends(PredicateCondition, _super);
+        function PredicateCondition(actionManager, predicate) {
+            _super.call(this, actionManager);
+            this.predicate = predicate;
+        }
+        PredicateCondition.prototype.isValid = function () {
+            return this.predicate();
+        };
+        return PredicateCondition;
+    }(Condition));
+    BABYLON.PredicateCondition = PredicateCondition;
+    var StateCondition = (function (_super) {
+        __extends(StateCondition, _super);
+        function StateCondition(actionManager, target, value) {
+            _super.call(this, actionManager);
+            this.value = value;
+            this._target = target;
+        }
+        // Methods
+        StateCondition.prototype.isValid = function () {
+            return this._target.state === this.value;
+        };
+        return StateCondition;
+    }(Condition));
+    BABYLON.StateCondition = StateCondition;
+})(BABYLON || (BABYLON = {}));

+ 204 - 204
src/Actions/babylon.directActions.js

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

+ 65 - 65
src/Actions/babylon.interpolateValueAction.js

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

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

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

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 671 - 671
src/Animations/babylon.animation.js


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

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

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

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

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

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

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 552 - 552
src/Audio/babylon.sound.js


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

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

+ 129 - 129
src/Bones/babylon.bone.js

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

+ 265 - 265
src/Bones/babylon.skeleton.js

@@ -1,265 +1,265 @@
-var BABYLON;
-(function (BABYLON) {
-    var Skeleton = (function () {
-        function Skeleton(name, id, scene) {
-            this.name = name;
-            this.id = id;
-            this.bones = new Array();
-            this.needInitialSkinMatrix = false;
-            this._isDirty = true;
-            this._meshesWithPoseMatrix = new Array();
-            this._identity = BABYLON.Matrix.Identity();
-            this._ranges = {};
-            this.bones = [];
-            this._scene = scene;
-            scene.skeletons.push(this);
-            this.prepare();
-            //make sure it will recalculate the matrix next time prepare is called.
-            this._isDirty = true;
-        }
-        // Members
-        Skeleton.prototype.getTransformMatrices = function (mesh) {
-            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
-                return mesh._bonesTransformMatrices;
-            }
-            return this._transformMatrices;
-        };
-        Skeleton.prototype.getScene = function () {
-            return this._scene;
-        };
-        // Methods
-        Skeleton.prototype.createAnimationRange = function (name, from, to) {
-            // check name not already in use
-            if (!this._ranges[name]) {
-                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
-                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                    if (this.bones[i].animations[0]) {
-                        this.bones[i].animations[0].createRange(name, from, to);
-                    }
-                }
-            }
-        };
-        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
-            if (deleteFrames === void 0) { deleteFrames = true; }
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                if (this.bones[i].animations[0]) {
-                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
-                }
-            }
-            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
-        };
-        Skeleton.prototype.getAnimationRange = function (name) {
-            return this._ranges[name];
-        };
-        /**
-         *  note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
-         */
-        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
-            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
-            if (this._ranges[name] || !source.getAnimationRange(name)) {
-                return false;
-            }
-            var ret = true;
-            var frameOffset = this._getHighestAnimationFrame() + 1;
-            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
-            var boneDict = {};
-            var sourceBones = source.bones;
-            for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
-                boneDict[sourceBones[i].name] = sourceBones[i];
-            }
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                var boneName = this.bones[i].name;
-                var sourceBone = boneDict[boneName];
-                if (sourceBone) {
-                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
-                }
-                else {
-                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
-                    ret = false;
-                }
-            }
-            // do not call createAnimationRange(), since it also is done to bones, which was already done
-            var range = source.getAnimationRange(name);
-            this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
-            return ret;
-        };
-        Skeleton.prototype.returnToRest = function () {
-            for (var index = 0; index < this.bones.length; index++) {
-                this.bones[index].returnToRest();
-            }
-        };
-        Skeleton.prototype._getHighestAnimationFrame = function () {
-            var ret = 0;
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                if (this.bones[i].animations[0]) {
-                    var highest = this.bones[i].animations[0].getHighestFrame();
-                    if (ret < highest) {
-                        ret = highest;
-                    }
-                }
-            }
-            return ret;
-        };
-        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
-            var range = this.getAnimationRange(name);
-            if (!range) {
-                return null;
-            }
-            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
-        };
-        Skeleton.prototype._markAsDirty = function () {
-            this._isDirty = true;
-        };
-        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
-            this._meshesWithPoseMatrix.push(mesh);
-        };
-        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
-            var index = this._meshesWithPoseMatrix.indexOf(mesh);
-            if (index > -1) {
-                this._meshesWithPoseMatrix.splice(index, 1);
-            }
-        };
-        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
-            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 {
-                    if (initialSkinMatrix) {
-                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
-                    }
-                    else {
-                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
-                    }
-                }
-                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
-            }
-            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
-        };
-        Skeleton.prototype.prepare = function () {
-            if (!this._isDirty) {
-                return;
-            }
-            if (this.needInitialSkinMatrix) {
-                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
-                    var mesh = this._meshesWithPoseMatrix[index];
-                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
-                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
-                    }
-                    var poseMatrix = mesh.getPoseMatrix();
-                    // Prepare bones
-                    for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
-                        var bone = this.bones[boneIndex];
-                        if (!bone.getParent()) {
-                            var matrix = bone.getBaseMatrix();
-                            matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
-                            bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
-                        }
-                    }
-                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
-                }
-            }
-            else {
-                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
-                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
-                }
-                this._computeTransformMatrices(this._transformMatrices, null);
-            }
-            this._isDirty = false;
-            this._scene._activeBones += 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++) {
-                    this._animatables.push(this.bones[index]);
-                }
-            }
-            return this._animatables;
-        };
-        Skeleton.prototype.clone = function (name, id) {
-            var result = new 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().clone(), source.getRestPose().clone());
-                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
-            }
-            return result;
-        };
-        Skeleton.prototype.dispose = function () {
-            this._meshesWithPoseMatrix = [];
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            this.getScene().removeSkeleton(this);
-        };
-        Skeleton.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.bones = [];
-            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
-            for (var index = 0; index < this.bones.length; index++) {
-                var bone = this.bones[index];
-                var serializedBone = {
-                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
-                    name: bone.name,
-                    matrix: bone.getLocalMatrix().toArray(),
-                    rest: bone.getRestPose().toArray()
-                };
-                serializationObject.bones.push(serializedBone);
-                if (bone.length) {
-                    serializedBone.length = bone.length;
-                }
-                if (bone.animations && bone.animations.length > 0) {
-                    serializedBone.animation = bone.animations[0].serialize();
-                }
-                serializationObject.ranges = [];
-                for (var name in this._ranges) {
-                    var range = {};
-                    range.name = name;
-                    range.from = this._ranges[name].from;
-                    range.to = this._ranges[name].to;
-                    serializationObject.ranges.push(range);
-                }
-            }
-            return serializationObject;
-        };
-        Skeleton.Parse = function (parsedSkeleton, scene) {
-            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
-            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
-            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
-                var parsedBone = parsedSkeleton.bones[index];
-                var parentBone = null;
-                if (parsedBone.parentBoneIndex > -1) {
-                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
-                }
-                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
-                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
-                if (parsedBone.length) {
-                    bone.length = parsedBone.length;
-                }
-                if (parsedBone.animation) {
-                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
-                }
-            }
-            // placed after bones, so createAnimationRange can cascade down
-            if (parsedSkeleton.ranges) {
-                for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
-                    var data = parsedSkeleton.ranges[index];
-                    skeleton.createAnimationRange(data.name, data.from, data.to);
-                }
-            }
-            return skeleton;
-        };
-        return Skeleton;
-    })();
-    BABYLON.Skeleton = Skeleton;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Skeleton = (function () {
+        function Skeleton(name, id, scene) {
+            this.name = name;
+            this.id = id;
+            this.bones = new Array();
+            this.needInitialSkinMatrix = false;
+            this._isDirty = true;
+            this._meshesWithPoseMatrix = new Array();
+            this._identity = BABYLON.Matrix.Identity();
+            this._ranges = {};
+            this.bones = [];
+            this._scene = scene;
+            scene.skeletons.push(this);
+            this.prepare();
+            //make sure it will recalculate the matrix next time prepare is called.
+            this._isDirty = true;
+        }
+        // Members
+        Skeleton.prototype.getTransformMatrices = function (mesh) {
+            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
+                return mesh._bonesTransformMatrices;
+            }
+            return this._transformMatrices;
+        };
+        Skeleton.prototype.getScene = function () {
+            return this._scene;
+        };
+        // Methods
+        Skeleton.prototype.createAnimationRange = function (name, from, to) {
+            // check name not already in use
+            if (!this._ranges[name]) {
+                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
+                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                    if (this.bones[i].animations[0]) {
+                        this.bones[i].animations[0].createRange(name, from, to);
+                    }
+                }
+            }
+        };
+        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
+            if (deleteFrames === void 0) { deleteFrames = true; }
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                if (this.bones[i].animations[0]) {
+                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
+                }
+            }
+            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
+        };
+        Skeleton.prototype.getAnimationRange = function (name) {
+            return this._ranges[name];
+        };
+        /**
+         *  note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
+         */
+        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
+            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
+            if (this._ranges[name] || !source.getAnimationRange(name)) {
+                return false;
+            }
+            var ret = true;
+            var frameOffset = this._getHighestAnimationFrame() + 1;
+            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
+            var boneDict = {};
+            var sourceBones = source.bones;
+            for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
+                boneDict[sourceBones[i].name] = sourceBones[i];
+            }
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                var boneName = this.bones[i].name;
+                var sourceBone = boneDict[boneName];
+                if (sourceBone) {
+                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
+                }
+                else {
+                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
+                    ret = false;
+                }
+            }
+            // do not call createAnimationRange(), since it also is done to bones, which was already done
+            var range = source.getAnimationRange(name);
+            this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
+            return ret;
+        };
+        Skeleton.prototype.returnToRest = function () {
+            for (var index = 0; index < this.bones.length; index++) {
+                this.bones[index].returnToRest();
+            }
+        };
+        Skeleton.prototype._getHighestAnimationFrame = function () {
+            var ret = 0;
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                if (this.bones[i].animations[0]) {
+                    var highest = this.bones[i].animations[0].getHighestFrame();
+                    if (ret < highest) {
+                        ret = highest;
+                    }
+                }
+            }
+            return ret;
+        };
+        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
+            var range = this.getAnimationRange(name);
+            if (!range) {
+                return null;
+            }
+            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
+        };
+        Skeleton.prototype._markAsDirty = function () {
+            this._isDirty = true;
+        };
+        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
+            this._meshesWithPoseMatrix.push(mesh);
+        };
+        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
+            var index = this._meshesWithPoseMatrix.indexOf(mesh);
+            if (index > -1) {
+                this._meshesWithPoseMatrix.splice(index, 1);
+            }
+        };
+        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
+            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 {
+                    if (initialSkinMatrix) {
+                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
+                    }
+                    else {
+                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
+                    }
+                }
+                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
+            }
+            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
+        };
+        Skeleton.prototype.prepare = function () {
+            if (!this._isDirty) {
+                return;
+            }
+            if (this.needInitialSkinMatrix) {
+                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
+                    var mesh = this._meshesWithPoseMatrix[index];
+                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
+                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
+                    }
+                    var poseMatrix = mesh.getPoseMatrix();
+                    // Prepare bones
+                    for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
+                        var bone = this.bones[boneIndex];
+                        if (!bone.getParent()) {
+                            var matrix = bone.getBaseMatrix();
+                            matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
+                            bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
+                        }
+                    }
+                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
+                }
+            }
+            else {
+                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
+                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
+                }
+                this._computeTransformMatrices(this._transformMatrices, null);
+            }
+            this._isDirty = false;
+            this._scene._activeBones += 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++) {
+                    this._animatables.push(this.bones[index]);
+                }
+            }
+            return this._animatables;
+        };
+        Skeleton.prototype.clone = function (name, id) {
+            var result = new 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().clone(), source.getRestPose().clone());
+                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
+            }
+            return result;
+        };
+        Skeleton.prototype.dispose = function () {
+            this._meshesWithPoseMatrix = [];
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            this.getScene().removeSkeleton(this);
+        };
+        Skeleton.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.bones = [];
+            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var serializedBone = {
+                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
+                    name: bone.name,
+                    matrix: bone.getLocalMatrix().toArray(),
+                    rest: bone.getRestPose().toArray()
+                };
+                serializationObject.bones.push(serializedBone);
+                if (bone.length) {
+                    serializedBone.length = bone.length;
+                }
+                if (bone.animations && bone.animations.length > 0) {
+                    serializedBone.animation = bone.animations[0].serialize();
+                }
+                serializationObject.ranges = [];
+                for (var name in this._ranges) {
+                    var range = {};
+                    range.name = name;
+                    range.from = this._ranges[name].from;
+                    range.to = this._ranges[name].to;
+                    serializationObject.ranges.push(range);
+                }
+            }
+            return serializationObject;
+        };
+        Skeleton.Parse = function (parsedSkeleton, scene) {
+            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
+            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
+            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
+                var parsedBone = parsedSkeleton.bones[index];
+                var parentBone = null;
+                if (parsedBone.parentBoneIndex > -1) {
+                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
+                }
+                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
+                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
+                if (parsedBone.length) {
+                    bone.length = parsedBone.length;
+                }
+                if (parsedBone.animation) {
+                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
+                }
+            }
+            // placed after bones, so createAnimationRange can cascade down
+            if (parsedSkeleton.ranges) {
+                for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
+                    var data = parsedSkeleton.ranges[index];
+                    skeleton.createAnimationRange(data.name, data.from, data.to);
+                }
+            }
+            return skeleton;
+        };
+        return Skeleton;
+    }());
+    BABYLON.Skeleton = Skeleton;
+})(BABYLON || (BABYLON = {}));

+ 0 - 123
src/Cameras/Composable/babylon.composableCamera.js

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

+ 0 - 135
src/Cameras/Composable/babylon.composableCamera.ts

@@ -1,135 +0,0 @@
-module BABYLON {       
-    export class ComposableCamera extends TargetCamera {
-        @serializeAsVector3()
-        public ellipsoid = new Vector3(0.5, 1, 0.5);
-
-        @serialize()
-        public checkCollisions = false;
-
-        @serialize()
-        public applyGravity = false;
-        
-        public inputs : ComposableCameraInputsManager;
-
-        public onCollide: (collidedMesh: AbstractMesh) => void;
-        
-        private _collider = new Collider();
-        private _needMoveForGravity = false;
-        private _oldPosition = Vector3.Zero();
-        private _diffPosition = Vector3.Zero();
-        private _newPosition = Vector3.Zero();
-        public _attachedElement: HTMLElement;
-        public _noPreventDefault: boolean;
-        
-        public _localDirection: Vector3;
-        public _transformedDirection: Vector3;        
-        
-        constructor(name: string, position: Vector3, scene: Scene) {
-            super(name, position, scene);
-            this.inputs = new ComposableCameraInputsManager(this);
-            this.inputs.addKeyboard().addMouse();
-        }
-
-        // Controls
-        public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
-            if (this._attachedElement) {
-                return;
-            }
-            this._noPreventDefault = noPreventDefault;
-            this._attachedElement = element;
-
-            this.inputs.attachElement(element, noPreventDefault);
-        }        
-
-        public detachControl(element: HTMLElement): void {
-            if (this._attachedElement !== element) {
-                return;
-            }
-
-            this.inputs.detachElement(this._attachedElement);
-            this._attachedElement = null;
-            
-            this.cameraDirection = new Vector3(0, 0, 0);
-            this.cameraRotation = new Vector2(0, 0);
-        }
-
-        public _collideWithWorld(velocity: Vector3): void {
-            var globalPosition: Vector3;
-
-            if (this.parent) {
-                globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
-            } else {
-                globalPosition = this.position;
-            }
-
-            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
-            this._collider.radius = this.ellipsoid;
-
-            //no need for clone, as long as gravity is not on.
-            var actualVelocity = velocity;
-			
-            //add gravity to the velocity to prevent the dual-collision checking
-            if (this.applyGravity) {
-                //this prevents mending with cameraDirection, a global variable of the free camera class.
-                actualVelocity = velocity.add(this.getScene().gravity);
-            }
-
-            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
-
-        }
-
-        private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
-            //TODO move this to the collision coordinator!
-            if (this.getScene().workerCollisions)
-                newPosition.multiplyInPlace(this._collider.radius);
-
-            var updatePosition = (newPos) => {
-                this._newPosition.copyFrom(newPos);
-
-                this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
-
-                var oldPosition = this.position.clone();
-                if (this._diffPosition.length() > Engine.CollisionsEpsilon) {
-                    this.position.addInPlace(this._diffPosition);
-                    if (this.onCollide && collidedMesh) {
-                        this.onCollide(collidedMesh);
-                    }
-                }
-            }
-
-            updatePosition(newPosition);
-        }
-
-        public _checkInputs(): void {
-            if (!this._localDirection) {
-                this._localDirection = Vector3.Zero();
-                this._transformedDirection = Vector3.Zero();
-            }
-
-            this.inputs.checkInputs();
-
-            super._checkInputs();
-        }
-
-        public _decideIfNeedsToMove(): boolean {
-            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        }
-
-        public _updatePosition(): void {
-            if (this.checkCollisions && this.getScene().collisionsEnabled) {
-                this._collideWithWorld(this.cameraDirection);
-            } else {
-                this.position.addInPlace(this.cameraDirection);
-            }
-        }
-
-        public dispose(): void {
-            this.inputs.clear();
-            super.dispose();
-        }
-        
-        public getTypeName(): string {
-            return "FreeCamera";
-        }
-    }    
-} 

+ 12 - 12
src/Cameras/Composable/Inputs/babylon.camerainput.deviceorientation.js

@@ -6,8 +6,8 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
 };
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraDeviceOrientationInput = (function () {
-        function ComposableCameraDeviceOrientationInput() {
+    var FreeCameraDeviceOrientationInput = (function () {
+        function FreeCameraDeviceOrientationInput() {
             this._offsetX = null;
             this._offsetY = null;
             this._orientationGamma = 0;
@@ -19,15 +19,15 @@ var BABYLON;
             this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
             this._orientationChanged = this.orientationChanged.bind(this);
         }
-        ComposableCameraDeviceOrientationInput.prototype.attachCamera = function (camera) {
+        FreeCameraDeviceOrientationInput.prototype.attachCamera = function (camera) {
             this.camera = camera;
             window.addEventListener("resize", this._resetOrientationGamma, false);
             window.addEventListener("deviceorientation", this._orientationChanged);
         };
-        ComposableCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
+        FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
             this._initialOrientationGamma = null;
         };
-        ComposableCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
+        FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
             if (!this._initialOrientationGamma) {
                 this._initialOrientationGamma = evt.gamma;
                 this._initialOrientationBeta = evt.beta;
@@ -37,7 +37,7 @@ var BABYLON;
             this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
             this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
         };
-        ComposableCameraDeviceOrientationInput.prototype.detach = function () {
+        FreeCameraDeviceOrientationInput.prototype.detach = function () {
             window.removeEventListener("resize", this._resetOrientationGamma);
             window.removeEventListener("deviceorientation", this._orientationChanged);
             this._orientationGamma = 0;
@@ -45,7 +45,7 @@ var BABYLON;
             this._initialOrientationGamma = 0;
             this._initialOrientationBeta = 0;
         };
-        ComposableCameraDeviceOrientationInput.prototype.checkInputs = function () {
+        FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
             if (!this._offsetX) {
                 return;
             }
@@ -56,16 +56,16 @@ var BABYLON;
             BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
             camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
         };
-        ComposableCameraDeviceOrientationInput.prototype.getTypeName = function () {
+        FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
             return "deviceorientation";
         };
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
+        ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
-        return ComposableCameraDeviceOrientationInput;
+        ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
+        return FreeCameraDeviceOrientationInput;
     }());
-    BABYLON.ComposableCameraDeviceOrientationInput = ComposableCameraDeviceOrientationInput;
+    BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
 })(BABYLON || (BABYLON = {}));

+ 3 - 3
src/Cameras/Composable/Inputs/babylon.camerainput.deviceorientation.ts

@@ -1,6 +1,6 @@
 module BABYLON {
-    export class ComposableCameraDeviceOrientationInput implements IComposableCameraInput {
-        camera: ComposableCamera;
+    export class FreeCameraDeviceOrientationInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
 
         private _offsetX: number = null;
         private _offsetY: number = null;
@@ -22,7 +22,7 @@ module BABYLON {
             this._orientationChanged = this.orientationChanged.bind(this);
         }
 
-        attachCamera(camera: ComposableCamera) {
+        attachCamera(camera: FreeCamera) {
             this.camera = camera;
 
             window.addEventListener("resize", this._resetOrientationGamma, false);

+ 11 - 11
src/Cameras/Composable/Inputs/babylon.camerainput.gamepad.js

@@ -6,19 +6,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
 };
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraGamepadInput = (function () {
-        function ComposableCameraGamepadInput() {
+    var FreeCameraGamepadInput = (function () {
+        function FreeCameraGamepadInput() {
             var _this = this;
             this.gamepadAngularSensibility = 200;
             this.gamepadMoveSensibility = 40;
             this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
         }
-        ComposableCameraGamepadInput.prototype.attachCamera = function (camera) {
+        FreeCameraGamepadInput.prototype.attachCamera = function (camera) {
             this.camera = camera;
         };
-        ComposableCameraGamepadInput.prototype.detach = function () {
+        FreeCameraGamepadInput.prototype.detach = function () {
         };
-        ComposableCameraGamepadInput.prototype.checkInputs = function () {
+        FreeCameraGamepadInput.prototype.checkInputs = function () {
             if (this.gamepad) {
                 var camera = this.camera;
                 var LSValues = this.gamepad.leftStick;
@@ -38,22 +38,22 @@ var BABYLON;
                 camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
             }
         };
-        ComposableCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
+        FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
             // Only the first gamepad can control the camera
             if (gamepad.index === 0) {
                 this.gamepad = gamepad;
             }
         };
-        ComposableCameraGamepadInput.prototype.getTypeName = function () {
+        FreeCameraGamepadInput.prototype.getTypeName = function () {
             return "gamepad";
         };
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
+        ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
-        return ComposableCameraGamepadInput;
+        ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
+        return FreeCameraGamepadInput;
     }());
-    BABYLON.ComposableCameraGamepadInput = ComposableCameraGamepadInput;
+    BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
 })(BABYLON || (BABYLON = {}));

+ 3 - 3
src/Cameras/Composable/Inputs/babylon.camerainput.gamepad.ts

@@ -1,6 +1,6 @@
 module BABYLON {       
-    export class ComposableCameraGamepadInput implements IComposableCameraInput {
-        camera : ComposableCamera;
+    export class FreeCameraGamepadInput implements ICameraInput<FreeCamera> {
+        camera : FreeCamera;
         
         public gamepad: Gamepad;
         private _gamepads: Gamepads;
@@ -15,7 +15,7 @@ module BABYLON {
             this._gamepads = new Gamepads((gamepad: Gamepad) => { this._onNewGameConnected(gamepad); });
         }
         
-        attachCamera(camera : ComposableCamera){
+        attachCamera(camera : FreeCamera){
             this.camera = camera;
         }
         

+ 13 - 13
src/Cameras/Composable/Inputs/babylon.camerainput.keyboard.js

@@ -6,15 +6,15 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
 };
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraKeyboardMoveInput = (function () {
-        function ComposableCameraKeyboardMoveInput() {
+    var FreeCameraKeyboardMoveInput = (function () {
+        function FreeCameraKeyboardMoveInput() {
             this._keys = [];
             this.keysUp = [38];
             this.keysDown = [40];
             this.keysLeft = [37];
             this.keysRight = [39];
         }
-        ComposableCameraKeyboardMoveInput.prototype.attachCamera = function (camera) {
+        FreeCameraKeyboardMoveInput.prototype.attachCamera = function (camera) {
             var _this = this;
             this.camera = camera;
             if (this._onKeyDown === undefined) {
@@ -53,14 +53,14 @@ var BABYLON;
                 ]);
             }
         };
-        ComposableCameraKeyboardMoveInput.prototype.detach = function () {
+        FreeCameraKeyboardMoveInput.prototype.detach = function () {
             BABYLON.Tools.UnregisterTopRootEvents([
                 { name: "keydown", handler: this._onKeyDown },
                 { name: "keyup", handler: this._onKeyUp },
                 { name: "blur", handler: this._onLostFocus }
             ]);
         };
-        ComposableCameraKeyboardMoveInput.prototype.checkInputs = function () {
+        FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
             var camera = this.camera;
             // Keyboard
             for (var index = 0; index < this._keys.length; index++) {
@@ -83,25 +83,25 @@ var BABYLON;
                 camera.cameraDirection.addInPlace(camera._transformedDirection);
             }
         };
-        ComposableCameraKeyboardMoveInput.prototype.getTypeName = function () {
+        FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
             return "keyboardmove";
         };
-        ComposableCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
+        FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
             this._keys = [];
         };
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraKeyboardMoveInput.prototype, "keysUp", void 0);
+        ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraKeyboardMoveInput.prototype, "keysDown", void 0);
+        ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
+        ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraKeyboardMoveInput.prototype, "keysRight", void 0);
-        return ComposableCameraKeyboardMoveInput;
+        ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
+        return FreeCameraKeyboardMoveInput;
     }());
-    BABYLON.ComposableCameraKeyboardMoveInput = ComposableCameraKeyboardMoveInput;
+    BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
 })(BABYLON || (BABYLON = {}));

+ 3 - 3
src/Cameras/Composable/Inputs/babylon.camerainput.keyboard.ts

@@ -1,6 +1,6 @@
 module BABYLON {
-    export class ComposableCameraKeyboardMoveInput implements IComposableCameraInput {
-        camera: ComposableCamera;
+    export class FreeCameraKeyboardMoveInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
         private _keys = [];
         private _onKeyDown: (e: KeyboardEvent) => any;
         private _onKeyUp: (e: KeyboardEvent) => any;
@@ -17,7 +17,7 @@ module BABYLON {
         @serialize()
         public keysRight = [39];
 
-        attachCamera(camera: ComposableCamera) {
+        attachCamera(camera: FreeCamera) {
             this.camera = camera;
             
             if (this._onKeyDown === undefined) {

+ 10 - 10
src/Cameras/Composable/Inputs/babylon.camerainput.mouse.js

@@ -6,14 +6,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
 };
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraMouseInput = (function () {
-        function ComposableCameraMouseInput() {
+    var FreeCameraMouseInput = (function () {
+        function FreeCameraMouseInput() {
             this.angularSensibility = 2000.0;
         }
-        ComposableCameraMouseInput.prototype.attachCamera = function (camera) {
+        FreeCameraMouseInput.prototype.attachCamera = function (camera) {
             this.camera = camera;
         };
-        ComposableCameraMouseInput.prototype.attachElement = function (element, noPreventDefault) {
+        FreeCameraMouseInput.prototype.attachElement = function (element, noPreventDefault) {
             var _this = this;
             var previousPosition;
             this.attachedElement = element;
@@ -71,7 +71,7 @@ var BABYLON;
             element.addEventListener("mouseout", this._onMouseOut, false);
             element.addEventListener("mousemove", this._onMouseMove, false);
         };
-        ComposableCameraMouseInput.prototype.detachElement = function (element) {
+        FreeCameraMouseInput.prototype.detachElement = function (element) {
             if (this.attachedElement !== element) {
                 return;
             }
@@ -81,18 +81,18 @@ var BABYLON;
             element.removeEventListener("mousemove", this._onMouseMove);
             this.attachedElement = null;
         };
-        ComposableCameraMouseInput.prototype.detach = function () {
+        FreeCameraMouseInput.prototype.detach = function () {
             if (this.attachedElement) {
                 this.detachElement(this.attachedElement);
             }
         };
-        ComposableCameraMouseInput.prototype.getTypeName = function () {
+        FreeCameraMouseInput.prototype.getTypeName = function () {
             return "mouse";
         };
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraMouseInput.prototype, "angularSensibility", void 0);
-        return ComposableCameraMouseInput;
+        ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
+        return FreeCameraMouseInput;
     }());
-    BABYLON.ComposableCameraMouseInput = ComposableCameraMouseInput;
+    BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
 })(BABYLON || (BABYLON = {}));

+ 3 - 3
src/Cameras/Composable/Inputs/babylon.camerainput.mouse.ts

@@ -1,6 +1,6 @@
 module BABYLON {       
-    export class ComposableCameraMouseInput implements IComposableCameraInput {
-        camera : ComposableCamera;
+    export class FreeCameraMouseInput implements ICameraInput<FreeCamera> {
+        camera : FreeCamera;
         attachedElement : HTMLElement;
         
         @serialize()
@@ -11,7 +11,7 @@ module BABYLON {
         private _onMouseOut: (e: MouseEvent) => any;
         private _onMouseMove: (e: MouseEvent) => any;
         
-        attachCamera(camera : ComposableCamera){
+        attachCamera(camera : FreeCamera){
             this.camera = camera;
         }
         

+ 18 - 12
src/Cameras/Composable/Inputs/babylon.camerainput.touch.js

@@ -6,8 +6,8 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
 };
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraTouchInput = (function () {
-        function ComposableCameraTouchInput() {
+    var FreeCameraTouchInput = (function () {
+        function FreeCameraTouchInput() {
             this._offsetX = null;
             this._offsetY = null;
             this._pointerCount = 0;
@@ -15,10 +15,10 @@ var BABYLON;
             this.touchAngularSensibility = 200000.0;
             this.touchMoveSensibility = 250.0;
         }
-        ComposableCameraTouchInput.prototype.attachCamera = function (camera) {
+        FreeCameraTouchInput.prototype.attachCamera = function (camera) {
             this.camera = camera;
         };
-        ComposableCameraTouchInput.prototype.attachElement = function (element, noPreventDefault) {
+        FreeCameraTouchInput.prototype.attachElement = function (element, noPreventDefault) {
             var _this = this;
             var previousPosition;
             if (this._attachedElement) {
@@ -26,6 +26,10 @@ var BABYLON;
             }
             this._attachedElement = element;
             if (this._onPointerDown === undefined) {
+                this._onLostFocus = function (evt) {
+                    _this._offsetX = null;
+                    _this._offsetY = null;
+                };
                 this._onPointerDown = function (evt) {
                     if (evt.pointerType === "mouse") {
                         return;
@@ -79,22 +83,24 @@ var BABYLON;
                     _this._offsetY = -(evt.clientY - previousPosition.y);
                 };
             }
+            element.addEventListener("blur", this._onLostFocus);
             element.addEventListener("pointerdown", this._onPointerDown);
             element.addEventListener("pointerup", this._onPointerUp);
             element.addEventListener("pointerout", this._onPointerUp);
             element.addEventListener("pointermove", this._onPointerMove);
         };
-        ComposableCameraTouchInput.prototype.detachElement = function (element) {
+        FreeCameraTouchInput.prototype.detachElement = function (element) {
             if (this._attachedElement !== element) {
                 return;
             }
+            element.removeEventListener("blur", this._onLostFocus);
             element.removeEventListener("pointerdown", this._onPointerDown);
             element.removeEventListener("pointerup", this._onPointerUp);
             element.removeEventListener("pointerout", this._onPointerUp);
             element.removeEventListener("pointermove", this._onPointerMove);
             this._attachedElement = null;
         };
-        ComposableCameraTouchInput.prototype.checkInputs = function () {
+        FreeCameraTouchInput.prototype.checkInputs = function () {
             if (this._offsetX) {
                 var camera = this.camera;
                 camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
@@ -109,21 +115,21 @@ var BABYLON;
                 }
             }
         };
-        ComposableCameraTouchInput.prototype.detach = function () {
+        FreeCameraTouchInput.prototype.detach = function () {
             if (this._attachedElement) {
                 this.detachElement(this._attachedElement);
             }
         };
-        ComposableCameraTouchInput.prototype.getTypeName = function () {
+        FreeCameraTouchInput.prototype.getTypeName = function () {
             return "touch";
         };
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraTouchInput.prototype, "touchAngularSensibility", void 0);
+        ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
         __decorate([
             BABYLON.serialize()
-        ], ComposableCameraTouchInput.prototype, "touchMoveSensibility", void 0);
-        return ComposableCameraTouchInput;
+        ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
+        return FreeCameraTouchInput;
     }());
-    BABYLON.ComposableCameraTouchInput = ComposableCameraTouchInput;
+    BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
 })(BABYLON || (BABYLON = {}));

+ 12 - 6
src/Cameras/Composable/Inputs/babylon.camerainput.touch.ts

@@ -1,6 +1,6 @@
 module BABYLON {
-    export class ComposableCameraTouchInput implements IComposableCameraInput {
-        camera: ComposableCamera;
+    export class FreeCameraTouchInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
 
         private _offsetX: number = null;
         private _offsetY: number = null;
@@ -10,6 +10,7 @@ module BABYLON {
         private _onPointerDown: (e: PointerEvent) => any;
         private _onPointerUp: (e: PointerEvent) => any;
         private _onPointerMove: (e: PointerEvent) => any;
+        private _onLostFocus: (e: FocusEvent) => any;
 
         @serialize()
         public touchAngularSensibility: number = 200000.0;
@@ -17,10 +18,10 @@ module BABYLON {
         @serialize()
         public touchMoveSensibility: number = 250.0;
 
-        attachCamera(camera: ComposableCamera) {
+        attachCamera(camera: FreeCamera) {
             this.camera = camera;
         }
-
+        
         attachElement(element: HTMLElement, noPreventDefault?: boolean) {
             var previousPosition;
 
@@ -31,7 +32,11 @@ module BABYLON {
             this._attachedElement = element;
 
             if (this._onPointerDown === undefined) {
-
+                this._onLostFocus = (evt) => {
+                    this._offsetX = null;
+                    this._offsetY = null;
+                }
+                
                 this._onPointerDown = (evt) => {
 
                     if (evt.pointerType === "mouse") {
@@ -105,7 +110,7 @@ module BABYLON {
 
 
             }
-
+            element.addEventListener("blur", this._onLostFocus);
             element.addEventListener("pointerdown", this._onPointerDown);
             element.addEventListener("pointerup", this._onPointerUp);
             element.addEventListener("pointerout", this._onPointerUp);
@@ -117,6 +122,7 @@ module BABYLON {
                 return;
             }
 
+            element.removeEventListener("blur", this._onLostFocus);
             element.removeEventListener("pointerdown", this._onPointerDown);
             element.removeEventListener("pointerup", this._onPointerUp);
             element.removeEventListener("pointerout", this._onPointerUp);

+ 10 - 10
src/Cameras/Composable/Inputs/babylon.camerainput.virtualjoystick.js

@@ -1,15 +1,15 @@
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraVirtualJoystickInput = (function () {
-        function ComposableCameraVirtualJoystickInput() {
+    var FreeCameraVirtualJoystickInput = (function () {
+        function FreeCameraVirtualJoystickInput() {
         }
-        ComposableCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
+        FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
             return this._leftjoystick;
         };
-        ComposableCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
+        FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
             return this._rightjoystick;
         };
-        ComposableCameraVirtualJoystickInput.prototype.checkInputs = function () {
+        FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
             var camera = this.camera;
             var speed = camera._computeLocalCameraSpeed() * 50;
             var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
@@ -23,7 +23,7 @@ var BABYLON;
                 this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
             }
         };
-        ComposableCameraVirtualJoystickInput.prototype.attachCamera = function (camera) {
+        FreeCameraVirtualJoystickInput.prototype.attachCamera = function (camera) {
             this.camera = camera;
             this._leftjoystick = new BABYLON.VirtualJoystick(true);
             this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
@@ -36,13 +36,13 @@ var BABYLON;
             this._rightjoystick.setJoystickSensibility(0.05);
             this._rightjoystick.setJoystickColor("yellow");
         };
-        ComposableCameraVirtualJoystickInput.prototype.detach = function () {
+        FreeCameraVirtualJoystickInput.prototype.detach = function () {
             this._leftjoystick.releaseCanvas();
         };
-        ComposableCameraVirtualJoystickInput.prototype.getTypeName = function () {
+        FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
             return "touch";
         };
-        return ComposableCameraVirtualJoystickInput;
+        return FreeCameraVirtualJoystickInput;
     }());
-    BABYLON.ComposableCameraVirtualJoystickInput = ComposableCameraVirtualJoystickInput;
+    BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
 })(BABYLON || (BABYLON = {}));

+ 3 - 3
src/Cameras/Composable/Inputs/babylon.camerainput.virtualjoystick.ts

@@ -1,6 +1,6 @@
 module BABYLON {
-    export class ComposableCameraVirtualJoystickInput implements IComposableCameraInput {
-        camera: ComposableCamera;
+    export class FreeCameraVirtualJoystickInput implements ICameraInput<FreeCamera> {
+        camera: FreeCamera;
 
         private _leftjoystick: VirtualJoystick;
         private _rightjoystick: VirtualJoystick;
@@ -29,7 +29,7 @@ module BABYLON {
             }
         }
         
-        attachCamera(camera: ComposableCamera) {
+        attachCamera(camera: FreeCamera) {
             this.camera = camera;
             
             this._leftjoystick = new VirtualJoystick(true);

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

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

+ 50 - 50
src/Cameras/VR/babylon.vrDeviceOrientationCamera.js

@@ -1,50 +1,50 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var VRDeviceOrientationFreeCamera = (function (_super) {
-        __extends(VRDeviceOrientationFreeCamera, _super);
-        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this._alpha = 0;
-            this._beta = 0;
-            this._gamma = 0;
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
-        }
-        VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
-            this._alpha = +evt.alpha | 0;
-            this._beta = +evt.beta | 0;
-            this._gamma = +evt.gamma | 0;
-            if (this._gamma < 0) {
-                this._gamma = 90 + this._gamma;
-            }
-            else {
-                // Incline it in the correct angle.
-                this._gamma = 270 - this._gamma;
-            }
-            this.rotation.x = this._gamma / 180.0 * Math.PI;
-            this.rotation.y = -this._alpha / 180.0 * Math.PI;
-            this.rotation.z = this._beta / 180.0 * Math.PI;
-        };
-        VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
-            return "VRDeviceOrientationFreeCamera";
-        };
-        return VRDeviceOrientationFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var VRDeviceOrientationFreeCamera = (function (_super) {
+        __extends(VRDeviceOrientationFreeCamera, _super);
+        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this._alpha = 0;
+            this._beta = 0;
+            this._gamma = 0;
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
+        }
+        VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
+            this._alpha = +evt.alpha | 0;
+            this._beta = +evt.beta | 0;
+            this._gamma = +evt.gamma | 0;
+            if (this._gamma < 0) {
+                this._gamma = 90 + this._gamma;
+            }
+            else {
+                // Incline it in the correct angle.
+                this._gamma = 270 - this._gamma;
+            }
+            this.rotation.x = this._gamma / 180.0 * Math.PI;
+            this.rotation.y = -this._alpha / 180.0 * Math.PI;
+            this.rotation.z = this._beta / 180.0 * Math.PI;
+        };
+        VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
+            return "VRDeviceOrientationFreeCamera";
+        };
+        return VRDeviceOrientationFreeCamera;
+    }(BABYLON.FreeCamera));
+    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
+})(BABYLON || (BABYLON = {}));

+ 76 - 76
src/Cameras/VR/babylon.webVRCamera.js

@@ -1,76 +1,76 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var WebVRFreeCamera = (function (_super) {
-        __extends(WebVRFreeCamera, _super);
-        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this._hmdDevice = null;
-            this._sensorDevice = null;
-            this._cacheState = null;
-            this._cacheQuaternion = new BABYLON.Quaternion();
-            this._cacheRotation = BABYLON.Vector3.Zero();
-            this._vrEnabled = false;
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this._getWebVRDevices = this._getWebVRDevices.bind(this);
-        }
-        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
-            var size = devices.length;
-            var i = 0;
-            // Reset devices.
-            this._sensorDevice = null;
-            this._hmdDevice = null;
-            // Search for a HmdDevice.
-            while (i < size && this._hmdDevice === null) {
-                if (devices[i] instanceof HMDVRDevice) {
-                    this._hmdDevice = devices[i];
-                }
-                i++;
-            }
-            i = 0;
-            while (i < size && this._sensorDevice === null) {
-                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
-                    this._sensorDevice = devices[i];
-                }
-                i++;
-            }
-            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
-        };
-        WebVRFreeCamera.prototype._checkInputs = function () {
-            if (this._vrEnabled) {
-                this._cacheState = this._sensorDevice.getState();
-                this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
-                this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
-                this.rotation.x = -this._cacheRotation.x;
-                this.rotation.y = -this._cacheRotation.y;
-                this.rotation.z = this._cacheRotation.z;
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            if (navigator.getVRDevices) {
-                navigator.getVRDevices().then(this._getWebVRDevices);
-            }
-            else if (navigator.mozGetVRDevices) {
-                navigator.mozGetVRDevices(this._getWebVRDevices);
-            }
-        };
-        WebVRFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            this._vrEnabled = false;
-        };
-        WebVRFreeCamera.prototype.getTypeName = function () {
-            return "WebVRFreeCamera";
-        };
-        return WebVRFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var WebVRFreeCamera = (function (_super) {
+        __extends(WebVRFreeCamera, _super);
+        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this._hmdDevice = null;
+            this._sensorDevice = null;
+            this._cacheState = null;
+            this._cacheQuaternion = new BABYLON.Quaternion();
+            this._cacheRotation = BABYLON.Vector3.Zero();
+            this._vrEnabled = false;
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this._getWebVRDevices = this._getWebVRDevices.bind(this);
+        }
+        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
+            var size = devices.length;
+            var i = 0;
+            // Reset devices.
+            this._sensorDevice = null;
+            this._hmdDevice = null;
+            // Search for a HmdDevice.
+            while (i < size && this._hmdDevice === null) {
+                if (devices[i] instanceof HMDVRDevice) {
+                    this._hmdDevice = devices[i];
+                }
+                i++;
+            }
+            i = 0;
+            while (i < size && this._sensorDevice === null) {
+                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
+                    this._sensorDevice = devices[i];
+                }
+                i++;
+            }
+            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
+        };
+        WebVRFreeCamera.prototype._checkInputs = function () {
+            if (this._vrEnabled) {
+                this._cacheState = this._sensorDevice.getState();
+                this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
+                this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
+                this.rotation.x = -this._cacheRotation.x;
+                this.rotation.y = -this._cacheRotation.y;
+                this.rotation.z = this._cacheRotation.z;
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            if (navigator.getVRDevices) {
+                navigator.getVRDevices().then(this._getWebVRDevices);
+            }
+            else if (navigator.mozGetVRDevices) {
+                navigator.mozGetVRDevices(this._getWebVRDevices);
+            }
+        };
+        WebVRFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            this._vrEnabled = false;
+        };
+        WebVRFreeCamera.prototype.getTypeName = function () {
+            return "WebVRFreeCamera";
+        };
+        return WebVRFreeCamera;
+    }(BABYLON.FreeCamera));
+    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
+})(BABYLON || (BABYLON = {}));

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 672 - 672
src/Cameras/babylon.arcRotateCamera.js


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 612 - 612
src/Cameras/babylon.camera.js


+ 10 - 33
src/Cameras/Composable/babylon.cameraInputsManager.js

@@ -1,12 +1,12 @@
 var BABYLON;
 (function (BABYLON) {
-    var ComposableCameraInputsManager = (function () {
-        function ComposableCameraInputsManager(camera) {
+    var CameraInputsManager = (function () {
+        function CameraInputsManager(camera) {
             this.inputs = {};
             this.camera = camera;
             this.checkInputs = function () { };
         }
-        ComposableCameraInputsManager.prototype.add = function (input) {
+        CameraInputsManager.prototype.add = function (input) {
             var type = input.getTypeName();
             if (this.inputs[type]) {
                 BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
@@ -19,32 +19,29 @@ var BABYLON;
             if (input.checkInputs) {
                 this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
             }
-            if (this.camera._attachedElement && input.attachElement) {
-                input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
-            }
         };
-        ComposableCameraInputsManager.prototype._addCheckInputs = function (fn) {
+        CameraInputsManager.prototype._addCheckInputs = function (fn) {
             var current = this.checkInputs;
             return function () {
                 current();
                 fn();
             };
         };
-        ComposableCameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
+        CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
             for (var cam in this.inputs) {
                 var input = this.inputs[cam];
                 if (input.attachElement)
                     this.inputs[cam].attachElement(element, noPreventDefault);
             }
         };
-        ComposableCameraInputsManager.prototype.detachElement = function (element) {
+        CameraInputsManager.prototype.detachElement = function (element) {
             for (var cam in this.inputs) {
                 var input = this.inputs[cam];
                 if (input.detachElement)
                     this.inputs[cam].detachElement(element);
             }
         };
-        ComposableCameraInputsManager.prototype.rebuildInputCheck = function (element) {
+        CameraInputsManager.prototype.rebuildInputCheck = function (element) {
             this.checkInputs = function () { };
             for (var cam in this.inputs) {
                 var input = this.inputs[cam];
@@ -53,34 +50,14 @@ var BABYLON;
                 }
             }
         };
-        ComposableCameraInputsManager.prototype.clear = function () {
+        CameraInputsManager.prototype.clear = function () {
             for (var cam in this.inputs) {
                 this.inputs[cam].detach();
             }
             this.inputs = {};
             this.checkInputs = function () { };
         };
-        ComposableCameraInputsManager.prototype.addKeyboard = function () {
-            this.add(new BABYLON.ComposableCameraKeyboardMoveInput());
-            return this;
-        };
-        ComposableCameraInputsManager.prototype.addMouse = function () {
-            this.add(new BABYLON.ComposableCameraMouseInput());
-            return this;
-        };
-        ComposableCameraInputsManager.prototype.addGamepad = function () {
-            this.add(new BABYLON.ComposableCameraGamepadInput());
-            return this;
-        };
-        ComposableCameraInputsManager.prototype.addDeviceOrientation = function () {
-            this.add(new BABYLON.ComposableCameraDeviceOrientationInput());
-            return this;
-        };
-        ComposableCameraInputsManager.prototype.addTouch = function () {
-            this.add(new BABYLON.ComposableCameraTouchInput());
-            return this;
-        };
-        return ComposableCameraInputsManager;
+        return CameraInputsManager;
     }());
-    BABYLON.ComposableCameraInputsManager = ComposableCameraInputsManager;
+    BABYLON.CameraInputsManager = CameraInputsManager;
 })(BABYLON || (BABYLON = {}));

+ 16 - 43
src/Cameras/Composable/babylon.cameraInputsManager.ts

@@ -1,7 +1,7 @@
 module BABYLON {
-    export interface IComposableCameraInput {
-        camera: ComposableCamera;
-        attachCamera(camera: ComposableCamera);
+    export interface ICameraInput<TCamera extends BABYLON.Camera> {
+        camera: TCamera;
+        attachCamera(camera: TCamera);
         detach();        
         getTypeName(): string;
         
@@ -10,23 +10,23 @@ module BABYLON {
         checkInputs?: () => void;
     }
 
-    export interface ComposableCameraInputsMap {
-        [name: string]: IComposableCameraInput;
-        [idx: number]: IComposableCameraInput;
+    export interface CameraInputsMap<TCamera extends BABYLON.Camera> {
+        [name: string]: ICameraInput<TCamera>;
+        [idx: number]: ICameraInput<TCamera>;
     }
 
-    export class ComposableCameraInputsManager {
-        inputs: ComposableCameraInputsMap;
-        camera: ComposableCamera;
+    export class CameraInputsManager<TCamera extends BABYLON.Camera> {
+        inputs: CameraInputsMap<TCamera>;
+        camera: TCamera;
         checkInputs: () => void;
 
-        constructor(camera: ComposableCamera) {
+        constructor(camera: TCamera) {
             this.inputs = {};
             this.camera = camera;
             this.checkInputs = () => { };
         }
 
-        add(input: IComposableCameraInput) {
+        public add(input: ICameraInput<TCamera>) {
             var type = input.getTypeName();
             if (this.inputs[type]) {
                 Tools.Warn("camera input of type " + type + " already exists on camera");
@@ -42,9 +42,7 @@ module BABYLON {
                 this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
             }
 
-            if (this.camera._attachedElement && input.attachElement) {
-                input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
-            }
+            
         }
         
         private _addCheckInputs(fn){
@@ -55,7 +53,7 @@ module BABYLON {
             }
         }
 
-        attachElement(element: HTMLElement, noPreventDefault?: boolean) {
+        public attachElement(element: HTMLElement, noPreventDefault?: boolean) {
             for (var cam in this.inputs) {
                 var input = this.inputs[cam];
                 if (input.attachElement)
@@ -63,7 +61,7 @@ module BABYLON {
             }
         }
 
-        detachElement(element: HTMLElement) {
+        public detachElement(element: HTMLElement) {
             for (var cam in this.inputs) {
                 var input = this.inputs[cam];
                 if (input.detachElement)
@@ -71,7 +69,7 @@ module BABYLON {
             }
         }
 
-        rebuildInputCheck(element: HTMLElement) {
+        public rebuildInputCheck(element: HTMLElement) {
             this.checkInputs = () => { };
 
             for (var cam in this.inputs) {
@@ -82,7 +80,7 @@ module BABYLON {
             }
         }
 
-        clear() {
+        public clear() {
             for (var cam in this.inputs) {
                 this.inputs[cam].detach();
             }
@@ -90,30 +88,5 @@ module BABYLON {
             this.inputs = {};
             this.checkInputs = () => { };
         }
-        
-        addKeyboard(){
-            this.add(new ComposableCameraKeyboardMoveInput());
-            return this;
-        }
-        
-        addMouse(){
-            this.add(new ComposableCameraMouseInput());
-            return this;
-        }
-        
-        addGamepad(){
-            this.add(new ComposableCameraGamepadInput());
-            return this;
-        }
-        
-        addDeviceOrientation(){
-            this.add(new ComposableCameraDeviceOrientationInput());
-            return this;
-        }
-        
-        addTouch(){
-            this.add(new ComposableCameraTouchInput());
-            return this;
-        }
     }
 } 

+ 91 - 86
src/Cameras/babylon.deviceOrientationCamera.js

@@ -1,86 +1,91 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var DeviceOrientationCamera = (function (_super) {
-        __extends(DeviceOrientationCamera, _super);
-        function DeviceOrientationCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this._offsetX = null;
-            this._offsetY = null;
-            this._orientationGamma = 0;
-            this._orientationBeta = 0;
-            this._initialOrientationGamma = 0;
-            this._initialOrientationBeta = 0;
-            this.angularSensibility = 10000.0;
-            this.moveSensibility = 50.0;
-            window.addEventListener("resize", function () {
-                _this._initialOrientationGamma = null;
-            }, false);
-        }
-        DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
-            var _this = this;
-            if (this._attachedCanvas) {
-                return;
-            }
-            this._attachedCanvas = canvas;
-            if (!this._orientationChanged) {
-                this._orientationChanged = function (evt) {
-                    if (!_this._initialOrientationGamma) {
-                        _this._initialOrientationGamma = evt.gamma;
-                        _this._initialOrientationBeta = evt.beta;
-                    }
-                    _this._orientationGamma = evt.gamma;
-                    _this._orientationBeta = evt.beta;
-                    _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
-                    _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
-                };
-            }
-            window.addEventListener("deviceorientation", this._orientationChanged);
-        };
-        DeviceOrientationCamera.prototype.detachControl = function (canvas) {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-            window.removeEventListener("deviceorientation", this._orientationChanged);
-            this._attachedCanvas = null;
-            this._orientationGamma = 0;
-            this._orientationBeta = 0;
-            this._initialOrientationGamma = 0;
-            this._initialOrientationBeta = 0;
-        };
-        DeviceOrientationCamera.prototype._checkInputs = function () {
-            if (!this._offsetX) {
-                return;
-            }
-            this.cameraRotation.y -= this._offsetX / this.angularSensibility;
-            var speed = this._computeLocalCameraSpeed();
-            var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-            this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-            _super.prototype._checkInputs.call(this);
-        };
-        DeviceOrientationCamera.prototype.getTypeName = function () {
-            return "DeviceOrientationCamera";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
-        return DeviceOrientationCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var DeviceOrientationCamera = (function (_super) {
+        __extends(DeviceOrientationCamera, _super);
+        //         private _offsetX: number = null;
+        //         private _offsetY: number = null;
+        //         private _orientationGamma: number = 0;
+        //         private _orientationBeta: number = 0;
+        //         private _initialOrientationGamma: number = 0;
+        //         private _initialOrientationBeta: number = 0;
+        //         private _attachedCanvas: HTMLCanvasElement;
+        //         private _orientationChanged: (e: DeviceOrientationEvent) => any;
+        // 
+        //         @serialize()
+        //         public angularSensibility: number = 10000.0;
+        // 
+        //         @serialize()
+        //         public moveSensibility: number = 50.0;
+        function DeviceOrientationCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addDeviceOrientation();
+            // window.addEventListener("resize", () => {
+            //     this._initialOrientationGamma = null;
+            // }, false);
+        }
+        //         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+        //             if (this._attachedCanvas) {
+        //                 return;
+        //             }
+        //             this._attachedCanvas = canvas;
+        // 
+        //             if (!this._orientationChanged) {
+        //                 this._orientationChanged = (evt) => {
+        // 
+        //                     if (!this._initialOrientationGamma) {
+        //                             this._initialOrientationGamma = evt.gamma;
+        //                             this._initialOrientationBeta = evt.beta;
+        //                     }
+        // 
+        //                     this._orientationGamma = evt.gamma;
+        //                     this._orientationBeta = evt.beta;
+        //  
+        //                     this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
+        //                     this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
+        //                 };
+        //             }
+        // 
+        //             window.addEventListener("deviceorientation", this._orientationChanged);
+        //         }
+        // 
+        //         public detachControl(canvas: HTMLCanvasElement): void {
+        //             if (this._attachedCanvas !== canvas) {
+        //                 return;
+        //             }
+        // 
+        //             window.removeEventListener("deviceorientation", this._orientationChanged);
+        // 
+        //             this._attachedCanvas = null;
+        //             this._orientationGamma = 0;
+        //             this._orientationBeta = 0;
+        //             this._initialOrientationGamma = 0;
+        //             this._initialOrientationBeta = 0;
+        //         }
+        // 
+        //         public _checkInputs(): void {
+        //             if (!this._offsetX) {
+        //                 return;
+        //             }
+        //             this.cameraRotation.y -= this._offsetX / this.angularSensibility;
+        // 
+        //             var speed = this._computeLocalCameraSpeed();
+        //             var direction = new Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
+        // 
+        //             Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+        //             this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+        // 
+        //             super._checkInputs();
+        //         }
+        DeviceOrientationCamera.prototype.getTypeName = function () {
+            return "DeviceOrientationCamera";
+        };
+        return DeviceOrientationCamera;
+    }(BABYLON.FreeCamera));
+    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
+})(BABYLON || (BABYLON = {}));

+ 71 - 71
src/Cameras/babylon.deviceOrientationCamera.ts

@@ -1,82 +1,82 @@
 module BABYLON {
     // We're mainly based on the logic defined into the FreeCamera code
     export class DeviceOrientationCamera extends FreeCamera {
-        private _offsetX: number = null;
-        private _offsetY: number = null;
-        private _orientationGamma: number = 0;
-        private _orientationBeta: number = 0;
-        private _initialOrientationGamma: number = 0;
-        private _initialOrientationBeta: number = 0;
-        private _attachedCanvas: HTMLCanvasElement;
-        private _orientationChanged: (e: DeviceOrientationEvent) => any;
-
-        @serialize()
-        public angularSensibility: number = 10000.0;
-
-        @serialize()
-        public moveSensibility: number = 50.0;
+//         private _offsetX: number = null;
+//         private _offsetY: number = null;
+//         private _orientationGamma: number = 0;
+//         private _orientationBeta: number = 0;
+//         private _initialOrientationGamma: number = 0;
+//         private _initialOrientationBeta: number = 0;
+//         private _attachedCanvas: HTMLCanvasElement;
+//         private _orientationChanged: (e: DeviceOrientationEvent) => any;
+// 
+//         @serialize()
+//         public angularSensibility: number = 10000.0;
+// 
+//         @serialize()
+//         public moveSensibility: number = 50.0;
 
         constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);
-
-            window.addEventListener("resize", () => {
-                this._initialOrientationGamma = null;
-            }, false);
-        }
-
-        public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
-            if (this._attachedCanvas) {
-                return;
-            }
-            this._attachedCanvas = canvas;
-
-            if (!this._orientationChanged) {
-                this._orientationChanged = (evt) => {
-
-                    if (!this._initialOrientationGamma) {
-                            this._initialOrientationGamma = evt.gamma;
-                            this._initialOrientationBeta = evt.beta;
-                    }
-
-                    this._orientationGamma = evt.gamma;
-                    this._orientationBeta = evt.beta;
- 
-                    this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
-                    this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
-                };
-            }
-
-            window.addEventListener("deviceorientation", this._orientationChanged);
+            this.inputs.addDeviceOrientation();
+            // window.addEventListener("resize", () => {
+            //     this._initialOrientationGamma = null;
+            // }, false);
         }
 
-        public detachControl(canvas: HTMLCanvasElement): void {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-
-            window.removeEventListener("deviceorientation", this._orientationChanged);
-
-            this._attachedCanvas = null;
-            this._orientationGamma = 0;
-            this._orientationBeta = 0;
-            this._initialOrientationGamma = 0;
-            this._initialOrientationBeta = 0;
-        }
-
-        public _checkInputs(): void {
-            if (!this._offsetX) {
-                return;
-            }
-            this.cameraRotation.y -= this._offsetX / this.angularSensibility;
-
-            var speed = this._computeLocalCameraSpeed();
-            var direction = new Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
-
-            Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-            this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-
-            super._checkInputs();
-        }
+//         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+//             if (this._attachedCanvas) {
+//                 return;
+//             }
+//             this._attachedCanvas = canvas;
+// 
+//             if (!this._orientationChanged) {
+//                 this._orientationChanged = (evt) => {
+// 
+//                     if (!this._initialOrientationGamma) {
+//                             this._initialOrientationGamma = evt.gamma;
+//                             this._initialOrientationBeta = evt.beta;
+//                     }
+// 
+//                     this._orientationGamma = evt.gamma;
+//                     this._orientationBeta = evt.beta;
+//  
+//                     this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
+//                     this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
+//                 };
+//             }
+// 
+//             window.addEventListener("deviceorientation", this._orientationChanged);
+//         }
+// 
+//         public detachControl(canvas: HTMLCanvasElement): void {
+//             if (this._attachedCanvas !== canvas) {
+//                 return;
+//             }
+// 
+//             window.removeEventListener("deviceorientation", this._orientationChanged);
+// 
+//             this._attachedCanvas = null;
+//             this._orientationGamma = 0;
+//             this._orientationBeta = 0;
+//             this._initialOrientationGamma = 0;
+//             this._initialOrientationBeta = 0;
+//         }
+// 
+//         public _checkInputs(): void {
+//             if (!this._offsetX) {
+//                 return;
+//             }
+//             this.cameraRotation.y -= this._offsetX / this.angularSensibility;
+// 
+//             var speed = this._computeLocalCameraSpeed();
+//             var direction = new Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
+// 
+//             Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+//             this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+// 
+//             super._checkInputs();
+//         }
 
         public getTypeName(): string {
             return "DeviceOrientationCamera";

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

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

+ 157 - 261
src/Cameras/babylon.freeCamera.js

@@ -1,261 +1,157 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCamera = (function (_super) {
-        __extends(FreeCamera, _super);
-        function FreeCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
-            this.keysUp = [38];
-            this.keysDown = [40];
-            this.keysLeft = [37];
-            this.keysRight = [39];
-            this.checkCollisions = false;
-            this.applyGravity = false;
-            this.angularSensibility = 2000.0;
-            this._keys = [];
-            this._collider = new BABYLON.Collider();
-            this._needMoveForGravity = false;
-            this._oldPosition = BABYLON.Vector3.Zero();
-            this._diffPosition = BABYLON.Vector3.Zero();
-            this._newPosition = BABYLON.Vector3.Zero();
-            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
-                if (collidedMesh === void 0) { collidedMesh = null; }
-                //TODO move this to the collision coordinator!
-                if (_this.getScene().workerCollisions)
-                    newPosition.multiplyInPlace(_this._collider.radius);
-                var updatePosition = function (newPos) {
-                    _this._newPosition.copyFrom(newPos);
-                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
-                    var oldPosition = _this.position.clone();
-                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
-                        _this.position.addInPlace(_this._diffPosition);
-                        if (_this.onCollide && collidedMesh) {
-                            _this.onCollide(collidedMesh);
-                        }
-                    }
-                };
-                updatePosition(newPosition);
-            };
-        }
-        FreeCamera.prototype._onLostFocus = function (e) {
-            this._keys = [];
-        };
-        // Controls
-        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            var previousPosition;
-            var engine = this.getEngine();
-            if (this._attachedElement) {
-                return;
-            }
-            this._attachedElement = element;
-            if (this._onMouseDown === undefined) {
-                this._onMouseDown = function (evt) {
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseUp = function (evt) {
-                    previousPosition = null;
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseOut = function (evt) {
-                    previousPosition = null;
-                    _this._keys = [];
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseMove = function (evt) {
-                    if (!previousPosition && !engine.isPointerLock) {
-                        return;
-                    }
-                    var offsetX;
-                    var offsetY;
-                    if (!engine.isPointerLock) {
-                        offsetX = evt.clientX - previousPosition.x;
-                        offsetY = evt.clientY - previousPosition.y;
-                    }
-                    else {
-                        offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
-                        offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
-                    }
-                    _this.cameraRotation.y += offsetX / _this.angularSensibility;
-                    _this.cameraRotation.x += offsetY / _this.angularSensibility;
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onKeyDown = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index === -1) {
-                            _this._keys.push(evt.keyCode);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                this._onKeyUp = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index >= 0) {
-                            _this._keys.splice(index, 1);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                this._reset = function () {
-                    _this._keys = [];
-                    previousPosition = null;
-                    _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
-                    _this.cameraRotation = new BABYLON.Vector2(0, 0);
-                };
-            }
-            element.addEventListener("mousedown", this._onMouseDown, false);
-            element.addEventListener("mouseup", this._onMouseUp, false);
-            element.addEventListener("mouseout", this._onMouseOut, false);
-            element.addEventListener("mousemove", this._onMouseMove, false);
-            BABYLON.Tools.RegisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        };
-        FreeCamera.prototype.detachControl = function (element) {
-            if (this._attachedElement !== element) {
-                return;
-            }
-            element.removeEventListener("mousedown", this._onMouseDown);
-            element.removeEventListener("mouseup", this._onMouseUp);
-            element.removeEventListener("mouseout", this._onMouseOut);
-            element.removeEventListener("mousemove", this._onMouseMove);
-            BABYLON.Tools.UnregisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-            this._attachedElement = null;
-            if (this._reset) {
-                this._reset();
-            }
-        };
-        FreeCamera.prototype._collideWithWorld = function (velocity) {
-            var globalPosition;
-            if (this.parent) {
-                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
-            }
-            else {
-                globalPosition = this.position;
-            }
-            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
-            this._collider.radius = this.ellipsoid;
-            //no need for clone, as long as gravity is not on.
-            var actualVelocity = velocity;
-            //add gravity to the velocity to prevent the dual-collision checking
-            if (this.applyGravity) {
-                //this prevents mending with cameraDirection, a global variable of the free camera class.
-                actualVelocity = velocity.add(this.getScene().gravity);
-            }
-            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
-        };
-        FreeCamera.prototype._checkInputs = function () {
-            if (!this._localDirection) {
-                this._localDirection = BABYLON.Vector3.Zero();
-                this._transformedDirection = BABYLON.Vector3.Zero();
-            }
-            // Keyboard
-            for (var index = 0; index < this._keys.length; index++) {
-                var keyCode = this._keys[index];
-                var speed = this._computeLocalCameraSpeed();
-                if (this.keysLeft.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(-speed, 0, 0);
-                }
-                else if (this.keysUp.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, speed);
-                }
-                else if (this.keysRight.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(speed, 0, 0);
-                }
-                else if (this.keysDown.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, -speed);
-                }
-                this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
-                BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
-                this.cameraDirection.addInPlace(this._transformedDirection);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        FreeCamera.prototype._decideIfNeedsToMove = function () {
-            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        };
-        FreeCamera.prototype._updatePosition = function () {
-            if (this.checkCollisions && this.getScene().collisionsEnabled) {
-                this._collideWithWorld(this.cameraDirection);
-            }
-            else {
-                this.position.addInPlace(this.cameraDirection);
-            }
-        };
-        FreeCamera.prototype.getTypeName = function () {
-            return "FreeCamera";
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], FreeCamera.prototype, "ellipsoid", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "keysUp", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "keysDown", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "keysLeft", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "keysRight", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "checkCollisions", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "applyGravity", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], FreeCamera.prototype, "angularSensibility", void 0);
-        return FreeCamera;
-    })(BABYLON.TargetCamera);
-    BABYLON.FreeCamera = FreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCamera = (function (_super) {
+        __extends(FreeCamera, _super);
+        function FreeCamera(name, position, scene) {
+            var _this = this;
+            _super.call(this, name, position, scene);
+            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
+            this.checkCollisions = false;
+            this.applyGravity = false;
+            this._collider = new BABYLON.Collider();
+            this._needMoveForGravity = false;
+            this._oldPosition = BABYLON.Vector3.Zero();
+            this._diffPosition = BABYLON.Vector3.Zero();
+            this._newPosition = BABYLON.Vector3.Zero();
+            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
+                if (collidedMesh === void 0) { collidedMesh = null; }
+                //TODO move this to the collision coordinator!
+                if (_this.getScene().workerCollisions)
+                    newPosition.multiplyInPlace(_this._collider.radius);
+                var updatePosition = function (newPos) {
+                    _this._newPosition.copyFrom(newPos);
+                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
+                    var oldPosition = _this.position.clone();
+                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
+                        _this.position.addInPlace(_this._diffPosition);
+                        if (_this.onCollide && collidedMesh) {
+                            _this.onCollide(collidedMesh);
+                        }
+                    }
+                };
+                updatePosition(newPosition);
+            };
+            this.inputs = new FreeCameraInputsManager(this);
+            this.inputs.addKeyboard().addMouse();
+        }
+        // Controls
+        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            if (this._attachedElement) {
+                return;
+            }
+            this._noPreventDefault = noPreventDefault;
+            this._attachedElement = element;
+            this.inputs.attachElement(element, noPreventDefault);
+        };
+        FreeCamera.prototype.detachControl = function (element) {
+            if (this._attachedElement !== element) {
+                return;
+            }
+            this.inputs.detachElement(this._attachedElement);
+            this._attachedElement = null;
+            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
+            this.cameraRotation = new BABYLON.Vector2(0, 0);
+        };
+        FreeCamera.prototype._collideWithWorld = function (velocity) {
+            var globalPosition;
+            if (this.parent) {
+                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
+            }
+            else {
+                globalPosition = this.position;
+            }
+            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
+            this._collider.radius = this.ellipsoid;
+            //no need for clone, as long as gravity is not on.
+            var actualVelocity = velocity;
+            //add gravity to the velocity to prevent the dual-collision checking
+            if (this.applyGravity) {
+                //this prevents mending with cameraDirection, a global variable of the free camera class.
+                actualVelocity = velocity.add(this.getScene().gravity);
+            }
+            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
+        };
+        FreeCamera.prototype._checkInputs = function () {
+            if (!this._localDirection) {
+                this._localDirection = BABYLON.Vector3.Zero();
+                this._transformedDirection = BABYLON.Vector3.Zero();
+            }
+            this.inputs.checkInputs();
+            _super.prototype._checkInputs.call(this);
+        };
+        FreeCamera.prototype._decideIfNeedsToMove = function () {
+            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+        };
+        FreeCamera.prototype._updatePosition = function () {
+            if (this.checkCollisions && this.getScene().collisionsEnabled) {
+                this._collideWithWorld(this.cameraDirection);
+            }
+            else {
+                this.position.addInPlace(this.cameraDirection);
+            }
+        };
+        FreeCamera.prototype.dispose = function () {
+            this.inputs.clear();
+            _super.prototype.dispose.call(this);
+        };
+        FreeCamera.prototype.getTypeName = function () {
+            return "FreeCamera";
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], FreeCamera.prototype, "ellipsoid", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCamera.prototype, "checkCollisions", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], FreeCamera.prototype, "applyGravity", void 0);
+        return FreeCamera;
+    }(BABYLON.TargetCamera));
+    BABYLON.FreeCamera = FreeCamera;
+    var FreeCameraInputsManager = (function (_super) {
+        __extends(FreeCameraInputsManager, _super);
+        function FreeCameraInputsManager(camera) {
+            _super.call(this, camera);
+        }
+        FreeCameraInputsManager.prototype.add = function (input) {
+            _super.prototype.add.call(this, input);
+            if (this.camera._attachedElement && input.attachElement) {
+                input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
+            }
+        };
+        FreeCameraInputsManager.prototype.addKeyboard = function () {
+            this.add(new BABYLON.FreeCameraKeyboardMoveInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addMouse = function () {
+            this.add(new BABYLON.FreeCameraMouseInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addGamepad = function () {
+            this.add(new BABYLON.FreeCameraGamepadInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
+            this.add(new BABYLON.FreeCameraDeviceOrientationInput());
+            return this;
+        };
+        FreeCameraInputsManager.prototype.addTouch = function () {
+            this.add(new BABYLON.FreeCameraTouchInput());
+            return this;
+        };
+        return FreeCameraInputsManager;
+    }(BABYLON.CameraInputsManager));
+    BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
+})(BABYLON || (BABYLON = {}));

+ 61 - 173
src/Cameras/babylon.freeCamera.ts

@@ -4,190 +4,53 @@
         public ellipsoid = new Vector3(0.5, 1, 0.5);
 
         @serialize()
-        public keysUp = [38];
-
-        @serialize()
-        public keysDown = [40];
-
-        @serialize()
-        public keysLeft = [37];
-
-        @serialize()
-        public keysRight = [39];
-
-        @serialize()
         public checkCollisions = false;
 
         @serialize()
         public applyGravity = false;
-
-        @serialize()
-        public angularSensibility = 2000.0;
+        
+        public inputs : FreeCameraInputsManager;
 
         public onCollide: (collidedMesh: AbstractMesh) => void;
-
-        private _keys = [];
+        
         private _collider = new Collider();
         private _needMoveForGravity = false;
         private _oldPosition = Vector3.Zero();
         private _diffPosition = Vector3.Zero();
         private _newPosition = Vector3.Zero();
-        private _attachedElement: HTMLElement;
-        private _localDirection: Vector3;
-        private _transformedDirection: Vector3;
-
-        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;        
+        public _attachedElement: HTMLElement;
+        public _noPreventDefault: boolean;
+        
+        public _localDirection: Vector3;
+        public _transformedDirection: Vector3;        
         
         constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);
-        }
-
-        public _onLostFocus(e: FocusEvent): void {
-            this._keys = [];
+            this.inputs = new FreeCameraInputsManager(this);
+            this.inputs.addKeyboard().addMouse();
         }
 
         // Controls
         public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
-            var previousPosition;
-            var engine = this.getEngine();
-
             if (this._attachedElement) {
                 return;
             }
+            this._noPreventDefault = noPreventDefault;
             this._attachedElement = element;
 
-            if (this._onMouseDown === undefined) {
-                this._onMouseDown = evt => {
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-
-                this._onMouseUp = evt => {
-                    previousPosition = null;
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-
-                this._onMouseOut = evt => {
-                    previousPosition = null;
-                    this._keys = [];
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-
-                this._onMouseMove = evt => {
-                    if (!previousPosition && !engine.isPointerLock) {
-                        return;
-                    }
-
-                    var offsetX;
-                    var offsetY;
-
-                    if (!engine.isPointerLock) {
-                        offsetX = evt.clientX - previousPosition.x;
-                        offsetY = evt.clientY - previousPosition.y;
-                    } else {
-                        offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
-                        offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
-                    }
-
-                    this.cameraRotation.y += offsetX / this.angularSensibility;
-                    this.cameraRotation.x += offsetY / this.angularSensibility;
-
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-
-                this._onKeyDown = evt => {
-                    if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = this._keys.indexOf(evt.keyCode);
-
-                        if (index === -1) {
-                            this._keys.push(evt.keyCode);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-
-                this._onKeyUp = evt => {
-                    if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = this._keys.indexOf(evt.keyCode);
-
-                        if (index >= 0) {
-                            this._keys.splice(index, 1);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-
-                this._reset = () => {
-                    this._keys = [];
-                    previousPosition = null;
-                    this.cameraDirection = new Vector3(0, 0, 0);
-                    this.cameraRotation = new Vector2(0, 0);
-                };
-            }
-
-            element.addEventListener("mousedown", this._onMouseDown, false);
-            element.addEventListener("mouseup", this._onMouseUp, false);
-            element.addEventListener("mouseout", this._onMouseOut, false);
-            element.addEventListener("mousemove", this._onMouseMove, false);
-
-            Tools.RegisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        }
+            this.inputs.attachElement(element, noPreventDefault);
+        }        
 
         public detachControl(element: HTMLElement): void {
             if (this._attachedElement !== element) {
                 return;
             }
 
-            element.removeEventListener("mousedown", this._onMouseDown);
-            element.removeEventListener("mouseup", this._onMouseUp);
-            element.removeEventListener("mouseout", this._onMouseOut);
-            element.removeEventListener("mousemove", this._onMouseMove);
-
-            Tools.UnregisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-
+            this.inputs.detachElement(this._attachedElement);
             this._attachedElement = null;
-            if (this._reset) {
-                this._reset();
-            }
+            
+            this.cameraDirection = new Vector3(0, 0, 0);
+            this.cameraRotation = new Vector2(0, 0);
         }
 
         public _collideWithWorld(velocity: Vector3): void {
@@ -243,25 +106,7 @@
                 this._transformedDirection = Vector3.Zero();
             }
 
-            // Keyboard
-            for (var index = 0; index < this._keys.length; index++) {
-                var keyCode = this._keys[index];
-                var speed = this._computeLocalCameraSpeed();
-
-                if (this.keysLeft.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(-speed, 0, 0);
-                } else if (this.keysUp.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, speed);
-                } else if (this.keysRight.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(speed, 0, 0);
-                } else if (this.keysDown.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, -speed);
-                }
-
-                this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
-                Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
-                this.cameraDirection.addInPlace(this._transformedDirection);
-            }
+            this.inputs.checkInputs();
 
             super._checkInputs();
         }
@@ -278,8 +123,51 @@
             }
         }
 
+        public dispose(): void {
+            this.inputs.clear();
+            super.dispose();
+        }
+        
         public getTypeName(): string {
             return "FreeCamera";
         }
     }
+    
+    export class FreeCameraInputsManager extends CameraInputsManager<FreeCamera> {
+        constructor(camera : FreeCamera){
+            super(camera);    
+        }
+        
+        add(input: ICameraInput<FreeCamera>){
+            super.add(input);
+            if (this.camera._attachedElement && input.attachElement) {
+                input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
+            }
+        }
+        
+        addKeyboard(){
+            this.add(new FreeCameraKeyboardMoveInput());
+            return this;
+        }
+        
+        addMouse(){
+            this.add(new FreeCameraMouseInput());
+            return this;
+        }
+        
+        addGamepad(){
+            this.add(new FreeCameraGamepadInput());
+            return this;
+        }
+        
+        addDeviceOrientation(){
+            this.add(new FreeCameraDeviceOrientationInput());
+            return this;
+        }
+        
+        addTouch(){
+            this.add(new FreeCameraTouchInput());
+            return this;
+        }
+    }
 } 

+ 21 - 21
src/Cameras/babylon.gamepadCamera.js

@@ -1,21 +1,21 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var GamepadCamera = (function (_super) {
-        __extends(GamepadCamera, _super);
-        function GamepadCamera(name, position, scene) {
-            BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
-            _super.call(this, name, position, scene);
-        }
-        GamepadCamera.prototype.getTypeName = function () {
-            return "GamepadCamera";
-        };
-        return GamepadCamera;
-    })(BABYLON.UniversalCamera);
-    BABYLON.GamepadCamera = GamepadCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var GamepadCamera = (function (_super) {
+        __extends(GamepadCamera, _super);
+        function GamepadCamera(name, position, scene) {
+            BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
+            _super.call(this, name, position, scene);
+        }
+        GamepadCamera.prototype.getTypeName = function () {
+            return "GamepadCamera";
+        };
+        return GamepadCamera;
+    }(BABYLON.UniversalCamera));
+    BABYLON.GamepadCamera = GamepadCamera;
+})(BABYLON || (BABYLON = {}));

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

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

+ 264 - 264
src/Cameras/babylon.targetCamera.js

@@ -1,264 +1,264 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var TargetCamera = (function (_super) {
-        __extends(TargetCamera, _super);
-        function TargetCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
-            this.cameraRotation = new BABYLON.Vector2(0, 0);
-            this.rotation = new BABYLON.Vector3(0, 0, 0);
-            this.speed = 2.0;
-            this.noRotationConstraint = false;
-            this.lockedTarget = null;
-            this._currentTarget = BABYLON.Vector3.Zero();
-            this._viewMatrix = BABYLON.Matrix.Zero();
-            this._camMatrix = BABYLON.Matrix.Zero();
-            this._cameraTransformMatrix = BABYLON.Matrix.Zero();
-            this._cameraRotationMatrix = BABYLON.Matrix.Zero();
-            this._referencePoint = new BABYLON.Vector3(0, 0, 1);
-            this._transformedReferencePoint = BABYLON.Vector3.Zero();
-            this._lookAtTemp = BABYLON.Matrix.Zero();
-            this._tempMatrix = BABYLON.Matrix.Zero();
-        }
-        TargetCamera.prototype.getFrontPosition = function (distance) {
-            var direction = this.getTarget().subtract(this.position);
-            direction.normalize();
-            direction.scaleInPlace(distance);
-            return this.globalPosition.add(direction);
-        };
-        TargetCamera.prototype._getLockedTargetPosition = function () {
-            if (!this.lockedTarget) {
-                return null;
-            }
-            return this.lockedTarget.position || this.lockedTarget;
-        };
-        // Cache
-        TargetCamera.prototype._initCache = function () {
-            _super.prototype._initCache.call(this);
-            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
-            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
-        };
-        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
-            if (!ignoreParentClass) {
-                _super.prototype._updateCache.call(this);
-            }
-            var lockedTargetPosition = this._getLockedTargetPosition();
-            if (!lockedTargetPosition) {
-                this._cache.lockedTarget = null;
-            }
-            else {
-                if (!this._cache.lockedTarget) {
-                    this._cache.lockedTarget = lockedTargetPosition.clone();
-                }
-                else {
-                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
-                }
-            }
-            this._cache.rotation.copyFrom(this.rotation);
-        };
-        // Synchronized
-        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
-            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
-                return false;
-            }
-            var lockedTargetPosition = this._getLockedTargetPosition();
-            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
-                && this._cache.rotation.equals(this.rotation);
-        };
-        // Methods
-        TargetCamera.prototype._computeLocalCameraSpeed = function () {
-            var engine = this.getEngine();
-            return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
-        };
-        // Target
-        TargetCamera.prototype.setTarget = function (target) {
-            this.upVector.normalize();
-            BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
-            this._camMatrix.invert();
-            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
-            var vDir = target.subtract(this.position);
-            if (vDir.x >= 0.0) {
-                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
-            }
-            else {
-                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
-            }
-            this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
-            if (isNaN(this.rotation.x)) {
-                this.rotation.x = 0;
-            }
-            if (isNaN(this.rotation.y)) {
-                this.rotation.y = 0;
-            }
-            if (isNaN(this.rotation.z)) {
-                this.rotation.z = 0;
-            }
-        };
-        TargetCamera.prototype.getTarget = function () {
-            return this._currentTarget;
-        };
-        TargetCamera.prototype._decideIfNeedsToMove = function () {
-            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        };
-        TargetCamera.prototype._updatePosition = function () {
-            this.position.addInPlace(this.cameraDirection);
-        };
-        TargetCamera.prototype._checkInputs = function () {
-            var needToMove = this._decideIfNeedsToMove();
-            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
-            // Move
-            if (needToMove) {
-                this._updatePosition();
-            }
-            // Rotate
-            if (needToRotate) {
-                this.rotation.x += this.cameraRotation.x;
-                this.rotation.y += this.cameraRotation.y;
-                if (!this.noRotationConstraint) {
-                    var limit = (Math.PI / 2) * 0.95;
-                    if (this.rotation.x > limit)
-                        this.rotation.x = limit;
-                    if (this.rotation.x < -limit)
-                        this.rotation.x = -limit;
-                }
-            }
-            // Inertia
-            if (needToMove) {
-                if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
-                    this.cameraDirection.x = 0;
-                }
-                if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
-                    this.cameraDirection.y = 0;
-                }
-                if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
-                    this.cameraDirection.z = 0;
-                }
-                this.cameraDirection.scaleInPlace(this.inertia);
-            }
-            if (needToRotate) {
-                if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
-                    this.cameraRotation.x = 0;
-                }
-                if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
-                    this.cameraRotation.y = 0;
-                }
-                this.cameraRotation.scaleInPlace(this.inertia);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        TargetCamera.prototype._getViewMatrix = function () {
-            if (!this.lockedTarget) {
-                // Compute
-                if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
-                    BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-                    this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
-                    this._lookAtTemp.invert();
-                    this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
-                }
-                else {
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
-                // Computing target and final matrix
-                this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
-            }
-            else {
-                this._currentTarget.copyFrom(this._getLockedTargetPosition());
-            }
-            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
-            return this._viewMatrix;
-        };
-        TargetCamera.prototype._getVRViewMatrix = function () {
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
-            BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
-            // Computing target and final matrix
-            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
-            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
-            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
-            return this._viewMatrix;
-        };
-        /**
-         * @override
-         * Override Camera.createRigCamera
-         */
-        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
-            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
-                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
-                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
-                    rigCamera._cameraRigParams = {};
-                    rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
-                    rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
-                }
-                return rigCamera;
-            }
-            return null;
-        };
-        /**
-         * @override
-         * Override Camera._updateRigCameras
-         */
-        TargetCamera.prototype._updateRigCameras = function () {
-            switch (this.cameraRigMode) {
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
-                case BABYLON.Camera.RIG_MODE_VR:
-                    var camLeft = this._rigCameras[0];
-                    var camRight = this._rigCameras[1];
-                    if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
-                        camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
-                        camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
-                        camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
-                        camLeft.position.copyFrom(this.position);
-                        camRight.position.copyFrom(this.position);
-                    }
-                    else {
-                        //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
-                        this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
-                        this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
-                        camLeft.setTarget(this.getTarget());
-                        camRight.setTarget(this.getTarget());
-                    }
-                    break;
-            }
-            _super.prototype._updateRigCameras.call(this);
-        };
-        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
-            if (!this._rigCamTransformMatrix) {
-                this._rigCamTransformMatrix = new BABYLON.Matrix();
-            }
-            var target = this.getTarget();
-            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
-            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
-            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
-        };
-        TargetCamera.prototype.getTypeName = function () {
-            return "TargetCamera";
-        };
-        __decorate([
-            BABYLON.serializeAsVector3()
-        ], TargetCamera.prototype, "rotation", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], TargetCamera.prototype, "speed", void 0);
-        __decorate([
-            BABYLON.serializeAsMeshReference("lockedTargetId")
-        ], TargetCamera.prototype, "lockedTarget", void 0);
-        return TargetCamera;
-    })(BABYLON.Camera);
-    BABYLON.TargetCamera = TargetCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var TargetCamera = (function (_super) {
+        __extends(TargetCamera, _super);
+        function TargetCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
+            this.cameraRotation = new BABYLON.Vector2(0, 0);
+            this.rotation = new BABYLON.Vector3(0, 0, 0);
+            this.speed = 2.0;
+            this.noRotationConstraint = false;
+            this.lockedTarget = null;
+            this._currentTarget = BABYLON.Vector3.Zero();
+            this._viewMatrix = BABYLON.Matrix.Zero();
+            this._camMatrix = BABYLON.Matrix.Zero();
+            this._cameraTransformMatrix = BABYLON.Matrix.Zero();
+            this._cameraRotationMatrix = BABYLON.Matrix.Zero();
+            this._referencePoint = new BABYLON.Vector3(0, 0, 1);
+            this._transformedReferencePoint = BABYLON.Vector3.Zero();
+            this._lookAtTemp = BABYLON.Matrix.Zero();
+            this._tempMatrix = BABYLON.Matrix.Zero();
+        }
+        TargetCamera.prototype.getFrontPosition = function (distance) {
+            var direction = this.getTarget().subtract(this.position);
+            direction.normalize();
+            direction.scaleInPlace(distance);
+            return this.globalPosition.add(direction);
+        };
+        TargetCamera.prototype._getLockedTargetPosition = function () {
+            if (!this.lockedTarget) {
+                return null;
+            }
+            return this.lockedTarget.position || this.lockedTarget;
+        };
+        // Cache
+        TargetCamera.prototype._initCache = function () {
+            _super.prototype._initCache.call(this);
+            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+        };
+        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
+            if (!ignoreParentClass) {
+                _super.prototype._updateCache.call(this);
+            }
+            var lockedTargetPosition = this._getLockedTargetPosition();
+            if (!lockedTargetPosition) {
+                this._cache.lockedTarget = null;
+            }
+            else {
+                if (!this._cache.lockedTarget) {
+                    this._cache.lockedTarget = lockedTargetPosition.clone();
+                }
+                else {
+                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
+                }
+            }
+            this._cache.rotation.copyFrom(this.rotation);
+        };
+        // Synchronized
+        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
+            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
+                return false;
+            }
+            var lockedTargetPosition = this._getLockedTargetPosition();
+            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
+                && this._cache.rotation.equals(this.rotation);
+        };
+        // Methods
+        TargetCamera.prototype._computeLocalCameraSpeed = function () {
+            var engine = this.getEngine();
+            return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
+        };
+        // Target
+        TargetCamera.prototype.setTarget = function (target) {
+            this.upVector.normalize();
+            BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
+            this._camMatrix.invert();
+            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
+            var vDir = target.subtract(this.position);
+            if (vDir.x >= 0.0) {
+                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
+            }
+            else {
+                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
+            }
+            this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
+            if (isNaN(this.rotation.x)) {
+                this.rotation.x = 0;
+            }
+            if (isNaN(this.rotation.y)) {
+                this.rotation.y = 0;
+            }
+            if (isNaN(this.rotation.z)) {
+                this.rotation.z = 0;
+            }
+        };
+        TargetCamera.prototype.getTarget = function () {
+            return this._currentTarget;
+        };
+        TargetCamera.prototype._decideIfNeedsToMove = function () {
+            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+        };
+        TargetCamera.prototype._updatePosition = function () {
+            this.position.addInPlace(this.cameraDirection);
+        };
+        TargetCamera.prototype._checkInputs = function () {
+            var needToMove = this._decideIfNeedsToMove();
+            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
+            // Move
+            if (needToMove) {
+                this._updatePosition();
+            }
+            // Rotate
+            if (needToRotate) {
+                this.rotation.x += this.cameraRotation.x;
+                this.rotation.y += this.cameraRotation.y;
+                if (!this.noRotationConstraint) {
+                    var limit = (Math.PI / 2) * 0.95;
+                    if (this.rotation.x > limit)
+                        this.rotation.x = limit;
+                    if (this.rotation.x < -limit)
+                        this.rotation.x = -limit;
+                }
+            }
+            // Inertia
+            if (needToMove) {
+                if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
+                    this.cameraDirection.x = 0;
+                }
+                if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
+                    this.cameraDirection.y = 0;
+                }
+                if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
+                    this.cameraDirection.z = 0;
+                }
+                this.cameraDirection.scaleInPlace(this.inertia);
+            }
+            if (needToRotate) {
+                if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
+                    this.cameraRotation.x = 0;
+                }
+                if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
+                    this.cameraRotation.y = 0;
+                }
+                this.cameraRotation.scaleInPlace(this.inertia);
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        TargetCamera.prototype._getViewMatrix = function () {
+            if (!this.lockedTarget) {
+                // Compute
+                if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
+                    BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
+                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+                    this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
+                    this._lookAtTemp.invert();
+                    this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
+                }
+                else {
+                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
+                // Computing target and final matrix
+                this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
+            }
+            else {
+                this._currentTarget.copyFrom(this._getLockedTargetPosition());
+            }
+            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
+            return this._viewMatrix;
+        };
+        TargetCamera.prototype._getVRViewMatrix = function () {
+            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
+            BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
+            // Computing target and final matrix
+            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
+            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
+            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
+            return this._viewMatrix;
+        };
+        /**
+         * @override
+         * Override Camera.createRigCamera
+         */
+        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
+            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
+                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
+                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
+                    rigCamera._cameraRigParams = {};
+                    rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
+                    rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
+                }
+                return rigCamera;
+            }
+            return null;
+        };
+        /**
+         * @override
+         * Override Camera._updateRigCameras
+         */
+        TargetCamera.prototype._updateRigCameras = function () {
+            switch (this.cameraRigMode) {
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
+                case BABYLON.Camera.RIG_MODE_VR:
+                    var camLeft = this._rigCameras[0];
+                    var camRight = this._rigCameras[1];
+                    if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
+                        camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
+                        camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
+                        camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
+                        camLeft.position.copyFrom(this.position);
+                        camRight.position.copyFrom(this.position);
+                    }
+                    else {
+                        //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
+                        this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
+                        this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
+                        camLeft.setTarget(this.getTarget());
+                        camRight.setTarget(this.getTarget());
+                    }
+                    break;
+            }
+            _super.prototype._updateRigCameras.call(this);
+        };
+        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
+            if (!this._rigCamTransformMatrix) {
+                this._rigCamTransformMatrix = new BABYLON.Matrix();
+            }
+            var target = this.getTarget();
+            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
+            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
+            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
+        };
+        TargetCamera.prototype.getTypeName = function () {
+            return "TargetCamera";
+        };
+        __decorate([
+            BABYLON.serializeAsVector3()
+        ], TargetCamera.prototype, "rotation", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], TargetCamera.prototype, "speed", void 0);
+        __decorate([
+            BABYLON.serializeAsMeshReference("lockedTargetId")
+        ], TargetCamera.prototype, "lockedTarget", void 0);
+        return TargetCamera;
+    }(BABYLON.Camera));
+    BABYLON.TargetCamera = TargetCamera;
+})(BABYLON || (BABYLON = {}));

+ 162 - 134
src/Cameras/babylon.touchCamera.js

@@ -1,134 +1,162 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var TouchCamera = (function (_super) {
-        __extends(TouchCamera, _super);
-        function TouchCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this._offsetX = null;
-            this._offsetY = null;
-            this._pointerCount = 0;
-            this._pointerPressed = [];
-            this.touchAngularSensibility = 200000.0;
-            this.touchMoveSensibility = 250.0;
-        }
-        TouchCamera.prototype._onLostFocus = function (e) {
-            this._offsetX = null;
-            this._offsetY = null;
-            _super.prototype._onLostFocus.call(this, e);
-        };
-        TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
-            var _this = this;
-            var previousPosition;
-            if (this._attachedCanvas) {
-                return;
-            }
-            if (this._onPointerDown === undefined) {
-                this._onPointerDown = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    _this._pointerPressed.push(evt.pointerId);
-                    if (_this._pointerPressed.length !== 1) {
-                        return;
-                    }
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                };
-                this._onPointerUp = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    var index = _this._pointerPressed.indexOf(evt.pointerId);
-                    if (index === -1) {
-                        return;
-                    }
-                    _this._pointerPressed.splice(index, 1);
-                    if (index != 0) {
-                        return;
-                    }
-                    previousPosition = null;
-                    _this._offsetX = null;
-                    _this._offsetY = null;
-                };
-                this._onPointerMove = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    if (!previousPosition) {
-                        return;
-                    }
-                    var index = _this._pointerPressed.indexOf(evt.pointerId);
-                    if (index != 0) {
-                        return;
-                    }
-                    _this._offsetX = evt.clientX - previousPosition.x;
-                    _this._offsetY = -(evt.clientY - previousPosition.y);
-                };
-            }
-            canvas.addEventListener("pointerdown", this._onPointerDown);
-            canvas.addEventListener("pointerup", this._onPointerUp);
-            canvas.addEventListener("pointerout", this._onPointerUp);
-            canvas.addEventListener("pointermove", this._onPointerMove);
-            _super.prototype.attachControl.call(this, canvas);
-        };
-        TouchCamera.prototype.detachControl = function (canvas) {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-            canvas.removeEventListener("pointerdown", this._onPointerDown);
-            canvas.removeEventListener("pointerup", this._onPointerUp);
-            canvas.removeEventListener("pointerout", this._onPointerUp);
-            canvas.removeEventListener("pointermove", this._onPointerMove);
-            _super.prototype.detachControl.call(this, canvas);
-        };
-        TouchCamera.prototype._checkInputs = function () {
-            if (this._offsetX) {
-                this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
-                if (this._pointerPressed.length > 1) {
-                    this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
-                }
-                else {
-                    var speed = this._computeLocalCameraSpeed();
-                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-                    this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-                }
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        TouchCamera.prototype.getTypeName = function () {
-            return "TouchCamera";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], TouchCamera.prototype, "touchAngularSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], TouchCamera.prototype, "touchMoveSensibility", void 0);
-        return TouchCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.TouchCamera = TouchCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var TouchCamera = (function (_super) {
+        __extends(TouchCamera, _super);
+        //         private _offsetX: number = null;
+        //         private _offsetY: number = null;
+        //         private _pointerCount:number = 0;
+        //         private _pointerPressed = [];
+        //         private _attachedCanvas: HTMLCanvasElement;
+        //         private _onPointerDown: (e: PointerEvent) => any;
+        //         private _onPointerUp: (e: PointerEvent) => any;
+        //         private _onPointerMove: (e: PointerEvent) => any;
+        // 
+        //         @serialize()
+        //         public touchAngularSensibility: number = 200000.0;
+        // 
+        //         @serialize()
+        //         public touchMoveSensibility: number = 250.0;
+        function TouchCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addTouch();
+        }
+        // public _onLostFocus(e: FocusEvent): void {
+        //     this._offsetX = null;
+        //     this._offsetY = null;
+        //     super._onLostFocus(e);
+        // }
+        //         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+        //             var previousPosition;
+        // 
+        //             if (this._attachedCanvas) {
+        //                 return;
+        //             }
+        // 
+        //             if (this._onPointerDown === undefined) {
+        // 
+        //                 this._onPointerDown = (evt) => {
+        // 
+        //                     if (evt.pointerType === "mouse") {
+        //                         return;
+        //                     }
+        // 
+        //                     if (!noPreventDefault) {
+        //                         evt.preventDefault();
+        //                     }
+        // 
+        //                     this._pointerPressed.push(evt.pointerId);
+        // 
+        //                     if (this._pointerPressed.length !== 1) {
+        //                         return;
+        //                     }
+        // 
+        //                     previousPosition = {
+        //                         x: evt.clientX,
+        //                         y: evt.clientY
+        //                     };
+        //                 };
+        // 
+        //                 this._onPointerUp = (evt) => {
+        // 
+        //                     if (evt.pointerType === "mouse") {
+        //                         return;
+        //                     }
+        // 
+        //                     if (!noPreventDefault) {
+        //                         evt.preventDefault();
+        //                     }
+        // 
+        //                     var index: number = this._pointerPressed.indexOf(evt.pointerId);
+        // 
+        //                     if (index === -1) {
+        //                         return;
+        //                     }
+        //                     this._pointerPressed.splice(index, 1);
+        // 
+        //                     if (index != 0) {
+        //                         return;
+        //                     }
+        //                     previousPosition = null;
+        //                     this._offsetX = null;
+        //                     this._offsetY = null;
+        //                 };
+        // 
+        //                 this._onPointerMove = (evt) => {
+        // 
+        //                     if (evt.pointerType === "mouse") {
+        //                         return;
+        //                     }
+        // 
+        //                     if (!noPreventDefault) {
+        //                         evt.preventDefault();
+        //                     }
+        // 
+        //                     if (!previousPosition) {
+        //                         return;
+        //                     }
+        // 
+        //                     var index: number = this._pointerPressed.indexOf(evt.pointerId);
+        // 
+        //                     if (index != 0) {
+        //                         return;
+        //                     }
+        // 
+        //                     this._offsetX = evt.clientX - previousPosition.x;
+        //                     this._offsetY = -(evt.clientY - previousPosition.y);
+        //                 };
+        // 
+        //                 
+        //             }
+        // 
+        //             canvas.addEventListener("pointerdown", this._onPointerDown);
+        //             canvas.addEventListener("pointerup", this._onPointerUp);
+        //             canvas.addEventListener("pointerout", this._onPointerUp);
+        //             canvas.addEventListener("pointermove", this._onPointerMove);
+        // 
+        //             super.attachControl(canvas);
+        //         }
+        // 
+        //         public detachControl(canvas: HTMLCanvasElement): void {
+        //             if (this._attachedCanvas !== canvas) {
+        //                 return;
+        //             }
+        // 
+        //             canvas.removeEventListener("pointerdown", this._onPointerDown);
+        //             canvas.removeEventListener("pointerup", this._onPointerUp);
+        //             canvas.removeEventListener("pointerout", this._onPointerUp);
+        //             canvas.removeEventListener("pointermove", this._onPointerMove);
+        //             
+        //             super.detachControl(canvas);
+        //         }
+        // 
+        //         public _checkInputs(): void {
+        //             if (this._offsetX) {
+        // 
+        //                 this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
+        // 
+        //                 if (this._pointerPressed.length > 1) {
+        //                     this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
+        //                 } else {
+        //                     var speed = this._computeLocalCameraSpeed();
+        //                     var direction = new Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
+        // 
+        //                     Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+        //                     this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+        //                 }
+        //             }
+        // 
+        //             super._checkInputs();
+        //         }
+        TouchCamera.prototype.getTypeName = function () {
+            return "TouchCamera";
+        };
+        return TouchCamera;
+    }(BABYLON.FreeCamera));
+    BABYLON.TouchCamera = TouchCamera;
+})(BABYLON || (BABYLON = {}));

+ 143 - 142
src/Cameras/babylon.touchCamera.ts

@@ -1,153 +1,154 @@
 module BABYLON {
     // We're mainly based on the logic defined into the FreeCamera code
     export class TouchCamera extends FreeCamera {
-        private _offsetX: number = null;
-        private _offsetY: number = null;
-        private _pointerCount:number = 0;
-        private _pointerPressed = [];
-        private _attachedCanvas: HTMLCanvasElement;
-        private _onPointerDown: (e: PointerEvent) => any;
-        private _onPointerUp: (e: PointerEvent) => any;
-        private _onPointerMove: (e: PointerEvent) => any;
-
-        @serialize()
-        public touchAngularSensibility: number = 200000.0;
-
-        @serialize()
-        public touchMoveSensibility: number = 250.0;
+//         private _offsetX: number = null;
+//         private _offsetY: number = null;
+//         private _pointerCount:number = 0;
+//         private _pointerPressed = [];
+//         private _attachedCanvas: HTMLCanvasElement;
+//         private _onPointerDown: (e: PointerEvent) => any;
+//         private _onPointerUp: (e: PointerEvent) => any;
+//         private _onPointerMove: (e: PointerEvent) => any;
+// 
+//         @serialize()
+//         public touchAngularSensibility: number = 200000.0;
+// 
+//         @serialize()
+//         public touchMoveSensibility: number = 250.0;
 
         constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);
+            this.inputs.addTouch();
         }
 
-        public _onLostFocus(e: FocusEvent): void {
-            this._offsetX = null;
-            this._offsetY = null;
-            super._onLostFocus(e);
-        }
-
-        public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
-            var previousPosition;
-
-            if (this._attachedCanvas) {
-                return;
-            }
-
-            if (this._onPointerDown === undefined) {
-
-                this._onPointerDown = (evt) => {
-
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-
-                    this._pointerPressed.push(evt.pointerId);
-
-                    if (this._pointerPressed.length !== 1) {
-                        return;
-                    }
-
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                };
-
-                this._onPointerUp = (evt) => {
-
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-
-                    var index: number = this._pointerPressed.indexOf(evt.pointerId);
-
-                    if (index === -1) {
-                        return;
-                    }
-                    this._pointerPressed.splice(index, 1);
-
-                    if (index != 0) {
-                        return;
-                    }
-                    previousPosition = null;
-                    this._offsetX = null;
-                    this._offsetY = null;
-                };
-
-                this._onPointerMove = (evt) => {
-
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-
-                    if (!previousPosition) {
-                        return;
-                    }
-
-                    var index: number = this._pointerPressed.indexOf(evt.pointerId);
-
-                    if (index != 0) {
-                        return;
-                    }
-
-                    this._offsetX = evt.clientX - previousPosition.x;
-                    this._offsetY = -(evt.clientY - previousPosition.y);
-                };
-
-                
-            }
-
-            canvas.addEventListener("pointerdown", this._onPointerDown);
-            canvas.addEventListener("pointerup", this._onPointerUp);
-            canvas.addEventListener("pointerout", this._onPointerUp);
-            canvas.addEventListener("pointermove", this._onPointerMove);
-
-            super.attachControl(canvas);
-        }
-
-        public detachControl(canvas: HTMLCanvasElement): void {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-
-            canvas.removeEventListener("pointerdown", this._onPointerDown);
-            canvas.removeEventListener("pointerup", this._onPointerUp);
-            canvas.removeEventListener("pointerout", this._onPointerUp);
-            canvas.removeEventListener("pointermove", this._onPointerMove);
-            
-            super.detachControl(canvas);
-        }
-
-        public _checkInputs(): void {
-            if (this._offsetX) {
-
-                this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
-
-                if (this._pointerPressed.length > 1) {
-                    this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
-                } else {
-                    var speed = this._computeLocalCameraSpeed();
-                    var direction = new Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
-
-                    Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-                    this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-                }
-            }
-
-            super._checkInputs();
-        }
+        // public _onLostFocus(e: FocusEvent): void {
+        //     this._offsetX = null;
+        //     this._offsetY = null;
+        //     super._onLostFocus(e);
+        // }
+
+//         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+//             var previousPosition;
+// 
+//             if (this._attachedCanvas) {
+//                 return;
+//             }
+// 
+//             if (this._onPointerDown === undefined) {
+// 
+//                 this._onPointerDown = (evt) => {
+// 
+//                     if (evt.pointerType === "mouse") {
+//                         return;
+//                     }
+// 
+//                     if (!noPreventDefault) {
+//                         evt.preventDefault();
+//                     }
+// 
+//                     this._pointerPressed.push(evt.pointerId);
+// 
+//                     if (this._pointerPressed.length !== 1) {
+//                         return;
+//                     }
+// 
+//                     previousPosition = {
+//                         x: evt.clientX,
+//                         y: evt.clientY
+//                     };
+//                 };
+// 
+//                 this._onPointerUp = (evt) => {
+// 
+//                     if (evt.pointerType === "mouse") {
+//                         return;
+//                     }
+// 
+//                     if (!noPreventDefault) {
+//                         evt.preventDefault();
+//                     }
+// 
+//                     var index: number = this._pointerPressed.indexOf(evt.pointerId);
+// 
+//                     if (index === -1) {
+//                         return;
+//                     }
+//                     this._pointerPressed.splice(index, 1);
+// 
+//                     if (index != 0) {
+//                         return;
+//                     }
+//                     previousPosition = null;
+//                     this._offsetX = null;
+//                     this._offsetY = null;
+//                 };
+// 
+//                 this._onPointerMove = (evt) => {
+// 
+//                     if (evt.pointerType === "mouse") {
+//                         return;
+//                     }
+// 
+//                     if (!noPreventDefault) {
+//                         evt.preventDefault();
+//                     }
+// 
+//                     if (!previousPosition) {
+//                         return;
+//                     }
+// 
+//                     var index: number = this._pointerPressed.indexOf(evt.pointerId);
+// 
+//                     if (index != 0) {
+//                         return;
+//                     }
+// 
+//                     this._offsetX = evt.clientX - previousPosition.x;
+//                     this._offsetY = -(evt.clientY - previousPosition.y);
+//                 };
+// 
+//                 
+//             }
+// 
+//             canvas.addEventListener("pointerdown", this._onPointerDown);
+//             canvas.addEventListener("pointerup", this._onPointerUp);
+//             canvas.addEventListener("pointerout", this._onPointerUp);
+//             canvas.addEventListener("pointermove", this._onPointerMove);
+// 
+//             super.attachControl(canvas);
+//         }
+// 
+//         public detachControl(canvas: HTMLCanvasElement): void {
+//             if (this._attachedCanvas !== canvas) {
+//                 return;
+//             }
+// 
+//             canvas.removeEventListener("pointerdown", this._onPointerDown);
+//             canvas.removeEventListener("pointerup", this._onPointerUp);
+//             canvas.removeEventListener("pointerout", this._onPointerUp);
+//             canvas.removeEventListener("pointermove", this._onPointerMove);
+//             
+//             super.detachControl(canvas);
+//         }
+// 
+//         public _checkInputs(): void {
+//             if (this._offsetX) {
+// 
+//                 this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
+// 
+//                 if (this._pointerPressed.length > 1) {
+//                     this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
+//                 } else {
+//                     var speed = this._computeLocalCameraSpeed();
+//                     var direction = new Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
+// 
+//                     Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+//                     this.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+//                 }
+//             }
+// 
+//             super._checkInputs();
+//         }
 
         public getTypeName(): string {
             return "TouchCamera";

+ 73 - 72
src/Cameras/babylon.universalCamera.js

@@ -1,72 +1,73 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var UniversalCamera = (function (_super) {
-        __extends(UniversalCamera, _super);
-        function UniversalCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this.gamepadAngularSensibility = 200;
-            this.gamepadMoveSensibility = 40;
-            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
-        }
-        UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
-            // Only the first gamepad can control the camera
-            if (gamepad.index === 0) {
-                this.gamepad = gamepad;
-            }
-        };
-        UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
-            _super.prototype.attachControl.call(this, canvas, false);
-        };
-        UniversalCamera.prototype.detachControl = function (canvas) {
-            _super.prototype.detachControl.call(this, canvas);
-        };
-        UniversalCamera.prototype._checkInputs = function () {
-            if (this.gamepad) {
-                var LSValues = this.gamepad.leftStick;
-                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
-                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
-                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
-                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
-                var RSValues = this.gamepad.rightStick;
-                var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
-                var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
-                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
-                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
-                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-                var speed = this._computeLocalCameraSpeed() * 50.0;
-                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
-                this.cameraDirection = this.cameraDirection.add(deltaTransform);
-                this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        UniversalCamera.prototype.dispose = function () {
-            this._gamepads.dispose();
-            _super.prototype.dispose.call(this);
-        };
-        UniversalCamera.prototype.getTypeName = function () {
-            return "UniversalCamera";
-        };
-        __decorate([
-            BABYLON.serialize()
-        ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
-        return UniversalCamera;
-    })(BABYLON.TouchCamera);
-    BABYLON.UniversalCamera = UniversalCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var UniversalCamera = (function (_super) {
+        __extends(UniversalCamera, _super);
+        //         public gamepad: Gamepad;
+        //         private _gamepads: Gamepads;
+        // 
+        //         @serialize()
+        //         public gamepadAngularSensibility = 200;
+        // 
+        //         @serialize()
+        //         public gamepadMoveSensibility = 40;
+        function UniversalCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addGamepad();
+            // this._gamepads = new Gamepads((gamepad: Gamepad) => { this._onNewGameConnected(gamepad); });
+        }
+        //         private _onNewGameConnected(gamepad: Gamepad) {
+        //             // Only the first gamepad can control the camera
+        //             if (gamepad.index === 0) {
+        //                 this.gamepad = gamepad;
+        //             }
+        //         }
+        // 
+        //         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+        //             super.attachControl(canvas, false);
+        //         }
+        // 
+        //         public detachControl(canvas: HTMLCanvasElement): void {
+        //             super.detachControl(canvas);
+        //         }
+        // 
+        //         public _checkInputs(): void {
+        //             if (this.gamepad) {
+        //                 var LSValues = this.gamepad.leftStick;
+        //                 var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
+        //                 var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
+        //                 LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
+        //                 LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
+        // 
+        //                 var RSValues = this.gamepad.rightStick;
+        //                 var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
+        //                 var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
+        //                 RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
+        //                 RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
+        // 
+        //                 var cameraTransform = Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+        // 
+        //                 var speed = this._computeLocalCameraSpeed() * 50.0;
+        //                 var deltaTransform = Vector3.TransformCoordinates(new Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
+        //                 this.cameraDirection = this.cameraDirection.add(deltaTransform);
+        //                 this.cameraRotation = this.cameraRotation.add(new Vector2(RSValues.y, RSValues.x));
+        //             }
+        //             super._checkInputs();
+        //         }
+        // 
+        //         public dispose(): void {
+        //             this._gamepads.dispose();
+        //             super.dispose();
+        //         }
+        UniversalCamera.prototype.getTypeName = function () {
+            return "UniversalCamera";
+        };
+        return UniversalCamera;
+    }(BABYLON.TouchCamera));
+    BABYLON.UniversalCamera = UniversalCamera;
+})(BABYLON || (BABYLON = {}));

+ 53 - 52
src/Cameras/babylon.universalCamera.ts

@@ -1,63 +1,64 @@
 module BABYLON {
     // We're mainly based on the logic defined into the FreeCamera code
     export class UniversalCamera extends TouchCamera {
-        public gamepad: Gamepad;
-        private _gamepads: Gamepads;
-
-        @serialize()
-        public gamepadAngularSensibility = 200;
-
-        @serialize()
-        public gamepadMoveSensibility = 40;
+//         public gamepad: Gamepad;
+//         private _gamepads: Gamepads;
+// 
+//         @serialize()
+//         public gamepadAngularSensibility = 200;
+// 
+//         @serialize()
+//         public gamepadMoveSensibility = 40;
 
         constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);
-            this._gamepads = new Gamepads((gamepad: Gamepad) => { this._onNewGameConnected(gamepad); });
-        }
-
-        private _onNewGameConnected(gamepad: Gamepad) {
-            // Only the first gamepad can control the camera
-            if (gamepad.index === 0) {
-                this.gamepad = gamepad;
-            }
-        }
-
-        public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
-            super.attachControl(canvas, false);
-        }
-
-        public detachControl(canvas: HTMLCanvasElement): void {
-            super.detachControl(canvas);
+            this.inputs.addGamepad();
+            // this._gamepads = new Gamepads((gamepad: Gamepad) => { this._onNewGameConnected(gamepad); });
         }
 
-        public _checkInputs(): void {
-            if (this.gamepad) {
-                var LSValues = this.gamepad.leftStick;
-                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
-                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
-                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
-                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
-
-                var RSValues = this.gamepad.rightStick;
-                var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
-                var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
-                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
-                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
-
-                var cameraTransform = Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-
-                var speed = this._computeLocalCameraSpeed() * 50.0;
-                var deltaTransform = Vector3.TransformCoordinates(new Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
-                this.cameraDirection = this.cameraDirection.add(deltaTransform);
-                this.cameraRotation = this.cameraRotation.add(new Vector2(RSValues.y, RSValues.x));
-            }
-            super._checkInputs();
-        }
-
-        public dispose(): void {
-            this._gamepads.dispose();
-            super.dispose();
-        }
+//         private _onNewGameConnected(gamepad: Gamepad) {
+//             // Only the first gamepad can control the camera
+//             if (gamepad.index === 0) {
+//                 this.gamepad = gamepad;
+//             }
+//         }
+// 
+//         public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
+//             super.attachControl(canvas, false);
+//         }
+// 
+//         public detachControl(canvas: HTMLCanvasElement): void {
+//             super.detachControl(canvas);
+//         }
+// 
+//         public _checkInputs(): void {
+//             if (this.gamepad) {
+//                 var LSValues = this.gamepad.leftStick;
+//                 var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
+//                 var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
+//                 LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
+//                 LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
+// 
+//                 var RSValues = this.gamepad.rightStick;
+//                 var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
+//                 var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
+//                 RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
+//                 RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
+// 
+//                 var cameraTransform = Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+// 
+//                 var speed = this._computeLocalCameraSpeed() * 50.0;
+//                 var deltaTransform = Vector3.TransformCoordinates(new Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
+//                 this.cameraDirection = this.cameraDirection.add(deltaTransform);
+//                 this.cameraRotation = this.cameraRotation.add(new Vector2(RSValues.y, RSValues.x));
+//             }
+//             super._checkInputs();
+//         }
+// 
+//         public dispose(): void {
+//             this._gamepads.dispose();
+//             super.dispose();
+//         }
 
         public getTypeName(): string {
             return "UniversalCamera";

+ 54 - 54
src/Cameras/babylon.virtualJoysticksCamera.js

@@ -1,54 +1,54 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var VirtualJoysticksCamera = (function (_super) {
-        __extends(VirtualJoysticksCamera, _super);
-        function VirtualJoysticksCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this._leftjoystick = new BABYLON.VirtualJoystick(true);
-            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
-            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
-            this._leftjoystick.setJoystickSensibility(0.15);
-            this._rightjoystick = new BABYLON.VirtualJoystick(false);
-            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
-            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
-            this._rightjoystick.reverseUpDown = true;
-            this._rightjoystick.setJoystickSensibility(0.05);
-            this._rightjoystick.setJoystickColor("yellow");
-        }
-        VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
-            return this._leftjoystick;
-        };
-        VirtualJoysticksCamera.prototype.getRightJoystick = function () {
-            return this._rightjoystick;
-        };
-        VirtualJoysticksCamera.prototype._checkInputs = function () {
-            var speed = this._computeLocalCameraSpeed() * 50;
-            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-            var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
-            this.cameraDirection = this.cameraDirection.add(deltaTransform);
-            this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
-            if (!this._leftjoystick.pressed) {
-                this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
-            }
-            if (!this._rightjoystick.pressed) {
-                this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        VirtualJoysticksCamera.prototype.dispose = function () {
-            this._leftjoystick.releaseCanvas();
-            _super.prototype.dispose.call(this);
-        };
-        VirtualJoysticksCamera.prototype.getTypeName = function () {
-            return "VirtualJoysticksCamera";
-        };
-        return VirtualJoysticksCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var VirtualJoysticksCamera = (function (_super) {
+        __extends(VirtualJoysticksCamera, _super);
+        function VirtualJoysticksCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this._leftjoystick = new BABYLON.VirtualJoystick(true);
+            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
+            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
+            this._leftjoystick.setJoystickSensibility(0.15);
+            this._rightjoystick = new BABYLON.VirtualJoystick(false);
+            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
+            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
+            this._rightjoystick.reverseUpDown = true;
+            this._rightjoystick.setJoystickSensibility(0.05);
+            this._rightjoystick.setJoystickColor("yellow");
+        }
+        VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
+            return this._leftjoystick;
+        };
+        VirtualJoysticksCamera.prototype.getRightJoystick = function () {
+            return this._rightjoystick;
+        };
+        VirtualJoysticksCamera.prototype._checkInputs = function () {
+            var speed = this._computeLocalCameraSpeed() * 50;
+            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+            var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
+            this.cameraDirection = this.cameraDirection.add(deltaTransform);
+            this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
+            if (!this._leftjoystick.pressed) {
+                this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
+            }
+            if (!this._rightjoystick.pressed) {
+                this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        VirtualJoysticksCamera.prototype.dispose = function () {
+            this._leftjoystick.releaseCanvas();
+            _super.prototype.dispose.call(this);
+        };
+        VirtualJoysticksCamera.prototype.getTypeName = function () {
+            return "VirtualJoysticksCamera";
+        };
+        return VirtualJoysticksCamera;
+    }(BABYLON.FreeCamera));
+    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
+})(BABYLON || (BABYLON = {}));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 171 - 171
src/Culling/babylon.ray.js

@@ -1,171 +1,171 @@
-var BABYLON;
-(function (BABYLON) {
-    var Ray = (function () {
-        function Ray(origin, direction, length) {
-            if (length === void 0) { length = Number.MAX_VALUE; }
-            this.origin = origin;
-            this.direction = direction;
-            this.length = length;
-        }
-        // Methods
-        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
-            var d = 0.0;
-            var maxValue = Number.MAX_VALUE;
-            var inv;
-            var min;
-            var max;
-            var temp;
-            if (Math.abs(this.direction.x) < 0.0000001) {
-                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.x;
-                min = (minimum.x - this.origin.x) * inv;
-                max = (maximum.x - this.origin.x) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            if (Math.abs(this.direction.y) < 0.0000001) {
-                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.y;
-                min = (minimum.y - this.origin.y) * inv;
-                max = (maximum.y - this.origin.y) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            if (Math.abs(this.direction.z) < 0.0000001) {
-                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
-                    return false;
-                }
-            }
-            else {
-                inv = 1.0 / this.direction.z;
-                min = (minimum.z - this.origin.z) * inv;
-                max = (maximum.z - this.origin.z) * inv;
-                if (max === -Infinity) {
-                    max = Infinity;
-                }
-                if (min > max) {
-                    temp = min;
-                    min = max;
-                    max = temp;
-                }
-                d = Math.max(min, d);
-                maxValue = Math.min(max, maxValue);
-                if (d > maxValue) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        Ray.prototype.intersectsBox = function (box) {
-            return this.intersectsBoxMinMax(box.minimum, box.maximum);
-        };
-        Ray.prototype.intersectsSphere = function (sphere) {
-            var x = sphere.center.x - this.origin.x;
-            var y = sphere.center.y - this.origin.y;
-            var z = sphere.center.z - this.origin.z;
-            var pyth = (x * x) + (y * y) + (z * z);
-            var rr = sphere.radius * sphere.radius;
-            if (pyth <= rr) {
-                return true;
-            }
-            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
-            if (dot < 0.0) {
-                return false;
-            }
-            var temp = pyth - (dot * dot);
-            return temp <= rr;
-        };
-        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
-            if (!this._edge1) {
-                this._edge1 = BABYLON.Vector3.Zero();
-                this._edge2 = BABYLON.Vector3.Zero();
-                this._pvec = BABYLON.Vector3.Zero();
-                this._tvec = BABYLON.Vector3.Zero();
-                this._qvec = BABYLON.Vector3.Zero();
-            }
-            vertex1.subtractToRef(vertex0, this._edge1);
-            vertex2.subtractToRef(vertex0, this._edge2);
-            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
-            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
-            if (det === 0) {
-                return null;
-            }
-            var invdet = 1 / det;
-            this.origin.subtractToRef(vertex0, this._tvec);
-            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
-            if (bu < 0 || bu > 1.0) {
-                return null;
-            }
-            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
-            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
-            if (bv < 0 || bu + bv > 1.0) {
-                return null;
-            }
-            //check if the distance is longer than the predefined length.
-            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
-            if (distance > this.length) {
-                return null;
-            }
-            return new BABYLON.IntersectionInfo(bu, bv, distance);
-        };
-        // Statics
-        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
-            var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
-            var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
-            var direction = end.subtract(start);
-            direction.normalize();
-            return new Ray(start, direction);
-        };
-        /**
-        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
-        * transformed to the given world matrix.
-        * @param origin The origin point
-        * @param end The end point
-        * @param world a matrix to transform the ray to. Default is the identity matrix.
-        */
-        Ray.CreateNewFromTo = function (origin, end, world) {
-            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
-            var direction = end.subtract(origin);
-            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
-            direction.normalize();
-            return Ray.Transform(new Ray(origin, direction, length), world);
-        };
-        Ray.Transform = function (ray, matrix) {
-            var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
-            var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
-            return new Ray(newOrigin, newDirection, ray.length);
-        };
-        return Ray;
-    })();
-    BABYLON.Ray = Ray;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Ray = (function () {
+        function Ray(origin, direction, length) {
+            if (length === void 0) { length = Number.MAX_VALUE; }
+            this.origin = origin;
+            this.direction = direction;
+            this.length = length;
+        }
+        // Methods
+        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
+            var d = 0.0;
+            var maxValue = Number.MAX_VALUE;
+            var inv;
+            var min;
+            var max;
+            var temp;
+            if (Math.abs(this.direction.x) < 0.0000001) {
+                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.x;
+                min = (minimum.x - this.origin.x) * inv;
+                max = (maximum.x - this.origin.x) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            if (Math.abs(this.direction.y) < 0.0000001) {
+                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.y;
+                min = (minimum.y - this.origin.y) * inv;
+                max = (maximum.y - this.origin.y) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            if (Math.abs(this.direction.z) < 0.0000001) {
+                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
+                    return false;
+                }
+            }
+            else {
+                inv = 1.0 / this.direction.z;
+                min = (minimum.z - this.origin.z) * inv;
+                max = (maximum.z - this.origin.z) * inv;
+                if (max === -Infinity) {
+                    max = Infinity;
+                }
+                if (min > max) {
+                    temp = min;
+                    min = max;
+                    max = temp;
+                }
+                d = Math.max(min, d);
+                maxValue = Math.min(max, maxValue);
+                if (d > maxValue) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        Ray.prototype.intersectsBox = function (box) {
+            return this.intersectsBoxMinMax(box.minimum, box.maximum);
+        };
+        Ray.prototype.intersectsSphere = function (sphere) {
+            var x = sphere.center.x - this.origin.x;
+            var y = sphere.center.y - this.origin.y;
+            var z = sphere.center.z - this.origin.z;
+            var pyth = (x * x) + (y * y) + (z * z);
+            var rr = sphere.radius * sphere.radius;
+            if (pyth <= rr) {
+                return true;
+            }
+            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
+            if (dot < 0.0) {
+                return false;
+            }
+            var temp = pyth - (dot * dot);
+            return temp <= rr;
+        };
+        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
+            if (!this._edge1) {
+                this._edge1 = BABYLON.Vector3.Zero();
+                this._edge2 = BABYLON.Vector3.Zero();
+                this._pvec = BABYLON.Vector3.Zero();
+                this._tvec = BABYLON.Vector3.Zero();
+                this._qvec = BABYLON.Vector3.Zero();
+            }
+            vertex1.subtractToRef(vertex0, this._edge1);
+            vertex2.subtractToRef(vertex0, this._edge2);
+            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
+            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
+            if (det === 0) {
+                return null;
+            }
+            var invdet = 1 / det;
+            this.origin.subtractToRef(vertex0, this._tvec);
+            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
+            if (bu < 0 || bu > 1.0) {
+                return null;
+            }
+            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
+            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
+            if (bv < 0 || bu + bv > 1.0) {
+                return null;
+            }
+            //check if the distance is longer than the predefined length.
+            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
+            if (distance > this.length) {
+                return null;
+            }
+            return new BABYLON.IntersectionInfo(bu, bv, distance);
+        };
+        // Statics
+        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
+            var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
+            var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
+            var direction = end.subtract(start);
+            direction.normalize();
+            return new Ray(start, direction);
+        };
+        /**
+        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
+        * transformed to the given world matrix.
+        * @param origin The origin point
+        * @param end The end point
+        * @param world a matrix to transform the ray to. Default is the identity matrix.
+        */
+        Ray.CreateNewFromTo = function (origin, end, world) {
+            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
+            var direction = end.subtract(origin);
+            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
+            direction.normalize();
+            return Ray.Transform(new Ray(origin, direction, length), world);
+        };
+        Ray.Transform = function (ray, matrix) {
+            var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
+            var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
+            return new Ray(newOrigin, newDirection, ray.length);
+        };
+        return Ray;
+    }());
+    BABYLON.Ray = Ray;
+})(BABYLON || (BABYLON = {}));

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 665 - 665
src/Debug/babylon.debugLayer.js


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

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

+ 95 - 95
src/Layer/babylon.layer.js

@@ -1,95 +1,95 @@
-var BABYLON;
-(function (BABYLON) {
-    var Layer = (function () {
-        function Layer(name, imgUrl, scene, isBackground, color) {
-            this.name = name;
-            this.scale = new BABYLON.Vector2(1, 1);
-            this.offset = new BABYLON.Vector2(0, 0);
-            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
-            this._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", "scale", "offset"], ["textureSampler"], "");
-            this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
-        }
-        Layer.prototype.render = function () {
-            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
-            // Check
-            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
-                return;
-            var engine = this._scene.getEngine();
-            if (this.onBeforeRender) {
-                this.onBeforeRender();
-            }
-            // Render
-            engine.enableEffect(currentEffect);
-            engine.setState(false);
-            // Texture
-            currentEffect.setTexture("textureSampler", this.texture);
-            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
-            // Color
-            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
-            // Scale / offset
-            currentEffect.setVector2("offset", this.offset);
-            currentEffect.setVector2("scale", this.scale);
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
-            // Draw order
-            if (!this._alphaTestEffect) {
-                engine.setAlphaMode(this.alphaBlendingMode);
-                engine.draw(true, 0, 6);
-                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-            }
-            else {
-                engine.draw(true, 0, 6);
-            }
-            if (this.onAfterRender) {
-                this.onAfterRender();
-            }
-        };
-        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 = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Layer = (function () {
+        function Layer(name, imgUrl, scene, isBackground, color) {
+            this.name = name;
+            this.scale = new BABYLON.Vector2(1, 1);
+            this.offset = new BABYLON.Vector2(0, 0);
+            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
+            this._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", "scale", "offset"], ["textureSampler"], "");
+            this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
+        }
+        Layer.prototype.render = function () {
+            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
+            // Check
+            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
+                return;
+            var engine = this._scene.getEngine();
+            if (this.onBeforeRender) {
+                this.onBeforeRender();
+            }
+            // Render
+            engine.enableEffect(currentEffect);
+            engine.setState(false);
+            // Texture
+            currentEffect.setTexture("textureSampler", this.texture);
+            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
+            // Color
+            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
+            // Scale / offset
+            currentEffect.setVector2("offset", this.offset);
+            currentEffect.setVector2("scale", this.scale);
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
+            // Draw order
+            if (!this._alphaTestEffect) {
+                engine.setAlphaMode(this.alphaBlendingMode);
+                engine.draw(true, 0, 6);
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            }
+            else {
+                engine.draw(true, 0, 6);
+            }
+            if (this.onAfterRender) {
+                this.onAfterRender();
+            }
+        };
+        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 = {}));

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

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

+ 208 - 208
src/LensFlare/babylon.lensFlareSystem.js

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

+ 405 - 405
src/Lights/Shadows/babylon.shadowGenerator.js

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

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

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

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

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

+ 162 - 162
src/Lights/babylon.light.js

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

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

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

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

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

+ 412 - 412
src/Loading/Plugins/babylon.babylonFileLoader.js

@@ -1,412 +1,412 @@
-var BABYLON;
-(function (BABYLON) {
-    var Internals;
-    (function (Internals) {
-        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
-            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                var parsedMaterial = parsedData.materials[index];
-                if (parsedMaterial.id === id) {
-                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                }
-            }
-            return null;
-        };
-        var isDescendantOf = function (mesh, names, hierarchyIds) {
-            names = (names instanceof Array) ? names : [names];
-            for (var i in names) {
-                if (mesh.name === names[i]) {
-                    hierarchyIds.push(mesh.id);
-                    return true;
-                }
-            }
-            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
-                hierarchyIds.push(mesh.id);
-                return true;
-            }
-            return false;
-        };
-        BABYLON.SceneLoader.RegisterPlugin({
-            extensions: ".babylon",
-            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
-                var parsedData = JSON.parse(data);
-                var loadedSkeletonsIds = [];
-                var loadedMaterialsIds = [];
-                var hierarchyIds = [];
-                var index;
-                var cache;
-                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                    var parsedMesh = parsedData.meshes[index];
-                    if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
-                        if (meshesNames instanceof Array) {
-                            // Remove found mesh name from list.
-                            delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
-                        }
-                        //Geometry?
-                        if (parsedMesh.geometryId) {
-                            //does the file contain geometries?
-                            if (parsedData.geometries) {
-                                //find the correct geometry and add it to the scene
-                                var found = false;
-                                ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
-                                    if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
-                                        return;
-                                    }
-                                    else {
-                                        parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
-                                            if (parsedGeometryData.id === parsedMesh.geometryId) {
-                                                switch (geometryType) {
-                                                    case "boxes":
-                                                        BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "spheres":
-                                                        BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "cylinders":
-                                                        BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "toruses":
-                                                        BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "grounds":
-                                                        BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "planes":
-                                                        BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "torusKnots":
-                                                        BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "vertexData":
-                                                        BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
-                                                        break;
-                                                }
-                                                found = true;
-                                            }
-                                        });
-                                    }
-                                });
-                                if (!found) {
-                                    BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
-                                }
-                            }
-                        }
-                        // Material ?
-                        if (parsedMesh.materialId) {
-                            var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
-                            if (!materialFound && parsedData.multiMaterials) {
-                                for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
-                                    var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
-                                    if (parsedMultiMaterial.id === parsedMesh.materialId) {
-                                        for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
-                                            var subMatId = parsedMultiMaterial.materials[matIndex];
-                                            loadedMaterialsIds.push(subMatId);
-                                            parseMaterialById(subMatId, parsedData, scene, rootUrl);
-                                        }
-                                        loadedMaterialsIds.push(parsedMultiMaterial.id);
-                                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                                        materialFound = true;
-                                        break;
-                                    }
-                                }
-                            }
-                            if (!materialFound) {
-                                loadedMaterialsIds.push(parsedMesh.materialId);
-                                if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
-                                    BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
-                                }
-                            }
-                        }
-                        // Skeleton ?
-                        if (parsedMesh.skeletonId > -1 && scene.skeletons) {
-                            var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
-                            if (!skeletonAlreadyLoaded) {
-                                for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
-                                    var parsedSkeleton = parsedData.skeletons[skeletonIndex];
-                                    if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                        skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
-                                        loadedSkeletonsIds.push(parsedSkeleton.id);
-                                    }
-                                }
-                            }
-                        }
-                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                        meshes.push(mesh);
-                    }
-                }
-                // Connecting parents
-                var currentMesh;
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingParentId) {
-                        currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
-                        currentMesh._waitingParentId = undefined;
-                    }
-                }
-                // freeze and compute world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = undefined;
-                    }
-                    else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
-                }
-                // Particles
-                if (parsedData.particleSystems) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                            particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
-                        }
-                    }
-                }
-                return true;
-            },
-            load: function (scene, data, rootUrl) {
-                var parsedData = JSON.parse(data);
-                // Scene
-                scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
-                scene.autoClear = parsedData.autoClear;
-                scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
-                scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
-                if (parsedData.gravity) {
-                    scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
-                }
-                // Fog
-                if (parsedData.fogMode && parsedData.fogMode !== 0) {
-                    scene.fogMode = parsedData.fogMode;
-                    scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
-                    scene.fogStart = parsedData.fogStart;
-                    scene.fogEnd = parsedData.fogEnd;
-                    scene.fogDensity = parsedData.fogDensity;
-                }
-                //Physics
-                if (parsedData.physicsEnabled) {
-                    var physicsPlugin;
-                    if (parsedData.physicsEngine === "cannon") {
-                        physicsPlugin = new BABYLON.CannonJSPlugin();
-                    }
-                    else if (parsedData.physicsEngine === "oimo") {
-                        physicsPlugin = new BABYLON.OimoJSPlugin();
-                    }
-                    //else - default engine, which is currently oimo
-                    var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
-                    scene.enablePhysics(physicsGravity, physicsPlugin);
-                }
-                //collisions, if defined. otherwise, default is true
-                if (parsedData.collisionsEnabled != undefined) {
-                    scene.collisionsEnabled = parsedData.collisionsEnabled;
-                }
-                scene.workerCollisions = !!parsedData.workerCollisions;
-                var index;
-                var cache;
-                // Lights
-                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
-                    var parsedLight = parsedData.lights[index];
-                    BABYLON.Light.Parse(parsedLight, scene);
-                }
-                // Animations
-                if (parsedData.animations) {
-                    for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
-                        var parsedAnimation = parsedData.animations[index];
-                        scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                    }
-                }
-                if (parsedData.autoAnimate) {
-                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
-                }
-                // Materials
-                if (parsedData.materials) {
-                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                        var parsedMaterial = parsedData.materials[index];
-                        BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                    }
-                }
-                if (parsedData.multiMaterials) {
-                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
-                        var parsedMultiMaterial = parsedData.multiMaterials[index];
-                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                    }
-                }
-                // Skeletons
-                if (parsedData.skeletons) {
-                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
-                        var parsedSkeleton = parsedData.skeletons[index];
-                        BABYLON.Skeleton.Parse(parsedSkeleton, scene);
-                    }
-                }
-                // Geometries
-                var geometries = parsedData.geometries;
-                if (geometries) {
-                    // Boxes
-                    var boxes = geometries.boxes;
-                    if (boxes) {
-                        for (index = 0, cache = boxes.length; index < cache; index++) {
-                            var parsedBox = boxes[index];
-                            BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
-                        }
-                    }
-                    // Spheres
-                    var spheres = geometries.spheres;
-                    if (spheres) {
-                        for (index = 0, cache = spheres.length; index < cache; index++) {
-                            var parsedSphere = spheres[index];
-                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
-                        }
-                    }
-                    // Cylinders
-                    var cylinders = geometries.cylinders;
-                    if (cylinders) {
-                        for (index = 0, cache = cylinders.length; index < cache; index++) {
-                            var parsedCylinder = cylinders[index];
-                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
-                        }
-                    }
-                    // Toruses
-                    var toruses = geometries.toruses;
-                    if (toruses) {
-                        for (index = 0, cache = toruses.length; index < cache; index++) {
-                            var parsedTorus = toruses[index];
-                            BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
-                        }
-                    }
-                    // Grounds
-                    var grounds = geometries.grounds;
-                    if (grounds) {
-                        for (index = 0, cache = grounds.length; index < cache; index++) {
-                            var parsedGround = grounds[index];
-                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
-                        }
-                    }
-                    // Planes
-                    var planes = geometries.planes;
-                    if (planes) {
-                        for (index = 0, cache = planes.length; index < cache; index++) {
-                            var parsedPlane = planes[index];
-                            BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
-                        }
-                    }
-                    // TorusKnots
-                    var torusKnots = geometries.torusKnots;
-                    if (torusKnots) {
-                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
-                            var parsedTorusKnot = torusKnots[index];
-                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
-                        }
-                    }
-                    // VertexData
-                    var vertexData = geometries.vertexData;
-                    if (vertexData) {
-                        for (index = 0, cache = vertexData.length; index < cache; index++) {
-                            var parsedVertexData = vertexData[index];
-                            BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
-                        }
-                    }
-                }
-                // Meshes
-                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                    var parsedMesh = parsedData.meshes[index];
-                    BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                }
-                // Cameras
-                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
-                    var parsedCamera = parsedData.cameras[index];
-                    BABYLON.Camera.Parse(parsedCamera, scene);
-                }
-                if (parsedData.activeCameraID) {
-                    scene.setActiveCameraByID(parsedData.activeCameraID);
-                }
-                // Browsing all the graph to connect the dots
-                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
-                    var camera = scene.cameras[index];
-                    if (camera._waitingParentId) {
-                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
-                        camera._waitingParentId = undefined;
-                    }
-                }
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    var light = scene.lights[index];
-                    if (light._waitingParentId) {
-                        light.parent = scene.getLastEntryByID(light._waitingParentId);
-                        light._waitingParentId = undefined;
-                    }
-                }
-                // Sounds
-                var loadedSounds = [];
-                var loadedSound;
-                if (BABYLON.AudioEngine && parsedData.sounds) {
-                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
-                        var parsedSound = parsedData.sounds[index];
-                        if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                            if (!parsedSound.url)
-                                parsedSound.url = parsedSound.name;
-                            if (!loadedSounds[parsedSound.url]) {
-                                loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
-                                loadedSounds[parsedSound.url] = loadedSound;
-                            }
-                            else {
-                                BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
-                            }
-                        }
-                        else {
-                            var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
-                        }
-                    }
-                }
-                loadedSounds = [];
-                // Connect parents & children and parse actions
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var mesh = scene.meshes[index];
-                    if (mesh._waitingParentId) {
-                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
-                        mesh._waitingParentId = undefined;
-                    }
-                    if (mesh._waitingActions) {
-                        BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
-                        mesh._waitingActions = undefined;
-                    }
-                }
-                // freeze world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = undefined;
-                    }
-                    else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
-                }
-                // Particles Systems
-                if (parsedData.particleSystems) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
-                    }
-                }
-                // Lens flares
-                if (parsedData.lensFlareSystems) {
-                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
-                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                        BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
-                    }
-                }
-                // Shadows
-                if (parsedData.shadowGenerators) {
-                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
-                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                        BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
-                    }
-                }
-                // Actions (scene)
-                if (parsedData.actions) {
-                    BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
-                }
-                // Finish
-                return true;
-            }
-        });
-    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Internals;
+    (function (Internals) {
+        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
+            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                var parsedMaterial = parsedData.materials[index];
+                if (parsedMaterial.id === id) {
+                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                }
+            }
+            return null;
+        };
+        var isDescendantOf = function (mesh, names, hierarchyIds) {
+            names = (names instanceof Array) ? names : [names];
+            for (var i in names) {
+                if (mesh.name === names[i]) {
+                    hierarchyIds.push(mesh.id);
+                    return true;
+                }
+            }
+            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
+                hierarchyIds.push(mesh.id);
+                return true;
+            }
+            return false;
+        };
+        BABYLON.SceneLoader.RegisterPlugin({
+            extensions: ".babylon",
+            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
+                var parsedData = JSON.parse(data);
+                var loadedSkeletonsIds = [];
+                var loadedMaterialsIds = [];
+                var hierarchyIds = [];
+                var index;
+                var cache;
+                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                    var parsedMesh = parsedData.meshes[index];
+                    if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
+                        if (meshesNames instanceof Array) {
+                            // Remove found mesh name from list.
+                            delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
+                        }
+                        //Geometry?
+                        if (parsedMesh.geometryId) {
+                            //does the file contain geometries?
+                            if (parsedData.geometries) {
+                                //find the correct geometry and add it to the scene
+                                var found = false;
+                                ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
+                                    if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
+                                        return;
+                                    }
+                                    else {
+                                        parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
+                                            if (parsedGeometryData.id === parsedMesh.geometryId) {
+                                                switch (geometryType) {
+                                                    case "boxes":
+                                                        BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "spheres":
+                                                        BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "cylinders":
+                                                        BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "toruses":
+                                                        BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "grounds":
+                                                        BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "planes":
+                                                        BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "torusKnots":
+                                                        BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "vertexData":
+                                                        BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
+                                                        break;
+                                                }
+                                                found = true;
+                                            }
+                                        });
+                                    }
+                                });
+                                if (!found) {
+                                    BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
+                                }
+                            }
+                        }
+                        // Material ?
+                        if (parsedMesh.materialId) {
+                            var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
+                            if (!materialFound && parsedData.multiMaterials) {
+                                for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
+                                    var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
+                                    if (parsedMultiMaterial.id === parsedMesh.materialId) {
+                                        for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
+                                            var subMatId = parsedMultiMaterial.materials[matIndex];
+                                            loadedMaterialsIds.push(subMatId);
+                                            parseMaterialById(subMatId, parsedData, scene, rootUrl);
+                                        }
+                                        loadedMaterialsIds.push(parsedMultiMaterial.id);
+                                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                                        materialFound = true;
+                                        break;
+                                    }
+                                }
+                            }
+                            if (!materialFound) {
+                                loadedMaterialsIds.push(parsedMesh.materialId);
+                                if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
+                                    BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
+                                }
+                            }
+                        }
+                        // Skeleton ?
+                        if (parsedMesh.skeletonId > -1 && scene.skeletons) {
+                            var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
+                            if (!skeletonAlreadyLoaded) {
+                                for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
+                                    var parsedSkeleton = parsedData.skeletons[skeletonIndex];
+                                    if (parsedSkeleton.id === parsedMesh.skeletonId) {
+                                        skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
+                                        loadedSkeletonsIds.push(parsedSkeleton.id);
+                                    }
+                                }
+                            }
+                        }
+                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                        meshes.push(mesh);
+                    }
+                }
+                // Connecting parents
+                var currentMesh;
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingParentId) {
+                        currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
+                        currentMesh._waitingParentId = undefined;
+                    }
+                }
+                // freeze and compute world matrix application
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingFreezeWorldMatrix) {
+                        currentMesh.freezeWorldMatrix();
+                        currentMesh._waitingFreezeWorldMatrix = undefined;
+                    }
+                    else {
+                        currentMesh.computeWorldMatrix(true);
+                    }
+                }
+                // Particles
+                if (parsedData.particleSystems) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
+                            particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
+                        }
+                    }
+                }
+                return true;
+            },
+            load: function (scene, data, rootUrl) {
+                var parsedData = JSON.parse(data);
+                // Scene
+                scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
+                scene.autoClear = parsedData.autoClear;
+                scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
+                scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
+                if (parsedData.gravity) {
+                    scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
+                }
+                // Fog
+                if (parsedData.fogMode && parsedData.fogMode !== 0) {
+                    scene.fogMode = parsedData.fogMode;
+                    scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
+                    scene.fogStart = parsedData.fogStart;
+                    scene.fogEnd = parsedData.fogEnd;
+                    scene.fogDensity = parsedData.fogDensity;
+                }
+                //Physics
+                if (parsedData.physicsEnabled) {
+                    var physicsPlugin;
+                    if (parsedData.physicsEngine === "cannon") {
+                        physicsPlugin = new BABYLON.CannonJSPlugin();
+                    }
+                    else if (parsedData.physicsEngine === "oimo") {
+                        physicsPlugin = new BABYLON.OimoJSPlugin();
+                    }
+                    //else - default engine, which is currently oimo
+                    var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
+                    scene.enablePhysics(physicsGravity, physicsPlugin);
+                }
+                //collisions, if defined. otherwise, default is true
+                if (parsedData.collisionsEnabled != undefined) {
+                    scene.collisionsEnabled = parsedData.collisionsEnabled;
+                }
+                scene.workerCollisions = !!parsedData.workerCollisions;
+                var index;
+                var cache;
+                // Lights
+                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
+                    var parsedLight = parsedData.lights[index];
+                    BABYLON.Light.Parse(parsedLight, scene);
+                }
+                // Animations
+                if (parsedData.animations) {
+                    for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
+                        var parsedAnimation = parsedData.animations[index];
+                        scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                    }
+                }
+                if (parsedData.autoAnimate) {
+                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
+                }
+                // Materials
+                if (parsedData.materials) {
+                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                        var parsedMaterial = parsedData.materials[index];
+                        BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                    }
+                }
+                if (parsedData.multiMaterials) {
+                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
+                        var parsedMultiMaterial = parsedData.multiMaterials[index];
+                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                    }
+                }
+                // Skeletons
+                if (parsedData.skeletons) {
+                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
+                        var parsedSkeleton = parsedData.skeletons[index];
+                        BABYLON.Skeleton.Parse(parsedSkeleton, scene);
+                    }
+                }
+                // Geometries
+                var geometries = parsedData.geometries;
+                if (geometries) {
+                    // Boxes
+                    var boxes = geometries.boxes;
+                    if (boxes) {
+                        for (index = 0, cache = boxes.length; index < cache; index++) {
+                            var parsedBox = boxes[index];
+                            BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
+                        }
+                    }
+                    // Spheres
+                    var spheres = geometries.spheres;
+                    if (spheres) {
+                        for (index = 0, cache = spheres.length; index < cache; index++) {
+                            var parsedSphere = spheres[index];
+                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
+                        }
+                    }
+                    // Cylinders
+                    var cylinders = geometries.cylinders;
+                    if (cylinders) {
+                        for (index = 0, cache = cylinders.length; index < cache; index++) {
+                            var parsedCylinder = cylinders[index];
+                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
+                        }
+                    }
+                    // Toruses
+                    var toruses = geometries.toruses;
+                    if (toruses) {
+                        for (index = 0, cache = toruses.length; index < cache; index++) {
+                            var parsedTorus = toruses[index];
+                            BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
+                        }
+                    }
+                    // Grounds
+                    var grounds = geometries.grounds;
+                    if (grounds) {
+                        for (index = 0, cache = grounds.length; index < cache; index++) {
+                            var parsedGround = grounds[index];
+                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
+                        }
+                    }
+                    // Planes
+                    var planes = geometries.planes;
+                    if (planes) {
+                        for (index = 0, cache = planes.length; index < cache; index++) {
+                            var parsedPlane = planes[index];
+                            BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
+                        }
+                    }
+                    // TorusKnots
+                    var torusKnots = geometries.torusKnots;
+                    if (torusKnots) {
+                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
+                            var parsedTorusKnot = torusKnots[index];
+                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
+                        }
+                    }
+                    // VertexData
+                    var vertexData = geometries.vertexData;
+                    if (vertexData) {
+                        for (index = 0, cache = vertexData.length; index < cache; index++) {
+                            var parsedVertexData = vertexData[index];
+                            BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
+                        }
+                    }
+                }
+                // Meshes
+                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                    var parsedMesh = parsedData.meshes[index];
+                    BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                }
+                // Cameras
+                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
+                    var parsedCamera = parsedData.cameras[index];
+                    BABYLON.Camera.Parse(parsedCamera, scene);
+                }
+                if (parsedData.activeCameraID) {
+                    scene.setActiveCameraByID(parsedData.activeCameraID);
+                }
+                // Browsing all the graph to connect the dots
+                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
+                    var camera = scene.cameras[index];
+                    if (camera._waitingParentId) {
+                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
+                        camera._waitingParentId = undefined;
+                    }
+                }
+                for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                    var light = scene.lights[index];
+                    if (light._waitingParentId) {
+                        light.parent = scene.getLastEntryByID(light._waitingParentId);
+                        light._waitingParentId = undefined;
+                    }
+                }
+                // Sounds
+                var loadedSounds = [];
+                var loadedSound;
+                if (BABYLON.AudioEngine && parsedData.sounds) {
+                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
+                        var parsedSound = parsedData.sounds[index];
+                        if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                            if (!parsedSound.url)
+                                parsedSound.url = parsedSound.name;
+                            if (!loadedSounds[parsedSound.url]) {
+                                loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
+                                loadedSounds[parsedSound.url] = loadedSound;
+                            }
+                            else {
+                                BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
+                            }
+                        }
+                        else {
+                            var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
+                        }
+                    }
+                }
+                loadedSounds = [];
+                // Connect parents & children and parse actions
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var mesh = scene.meshes[index];
+                    if (mesh._waitingParentId) {
+                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
+                        mesh._waitingParentId = undefined;
+                    }
+                    if (mesh._waitingActions) {
+                        BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                        mesh._waitingActions = undefined;
+                    }
+                }
+                // freeze world matrix application
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingFreezeWorldMatrix) {
+                        currentMesh.freezeWorldMatrix();
+                        currentMesh._waitingFreezeWorldMatrix = undefined;
+                    }
+                    else {
+                        currentMesh.computeWorldMatrix(true);
+                    }
+                }
+                // Particles Systems
+                if (parsedData.particleSystems) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                    }
+                }
+                // Lens flares
+                if (parsedData.lensFlareSystems) {
+                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
+                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                        BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                    }
+                }
+                // Shadows
+                if (parsedData.shadowGenerators) {
+                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
+                        BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                    }
+                }
+                // Actions (scene)
+                if (parsedData.actions) {
+                    BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
+                }
+                // Finish
+                return true;
+            }
+        });
+    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
+})(BABYLON || (BABYLON = {}));

+ 186 - 186
src/Loading/babylon.sceneLoader.js

@@ -1,186 +1,186 @@
-var BABYLON;
-(function (BABYLON) {
-    var SceneLoader = (function () {
-        function SceneLoader() {
-        }
-        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
-            get: function () {
-                return SceneLoader._ForceFullSceneLoadingForIncremental;
-            },
-            set: function (value) {
-                SceneLoader._ForceFullSceneLoadingForIncremental = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
-            get: function () {
-                return SceneLoader._ShowLoadingScreen;
-            },
-            set: function (value) {
-                SceneLoader._ShowLoadingScreen = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SceneLoader._getPluginForFilename = function (sceneFilename) {
-            var dotPosition = sceneFilename.lastIndexOf(".");
-            var queryStringPosition = sceneFilename.indexOf("?");
-            if (queryStringPosition === -1) {
-                queryStringPosition = sceneFilename.length;
-            }
-            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
-            for (var index = 0; index < this._registeredPlugins.length; index++) {
-                var plugin = this._registeredPlugins[index];
-                if (plugin.extensions.indexOf(extension) !== -1) {
-                    return plugin;
-                }
-            }
-            return this._registeredPlugins[this._registeredPlugins.length - 1];
-        };
-        // Public functions
-        SceneLoader.GetPluginForExtension = function (extension) {
-            for (var index = 0; index < this._registeredPlugins.length; index++) {
-                var plugin = this._registeredPlugins[index];
-                if (plugin.extensions.indexOf(extension) !== -1) {
-                    return plugin;
-                }
-            }
-            return null;
-        };
-        SceneLoader.RegisterPlugin = function (plugin) {
-            plugin.extensions = plugin.extensions.toLowerCase();
-            SceneLoader._registeredPlugins.push(plugin);
-        };
-        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            var manifestChecked = function (success) {
-                scene.database = database;
-                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
-                var importMeshFromData = function (data) {
-                    var meshes = [];
-                    var particleSystems = [];
-                    var skeletons = [];
-                    try {
-                        if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
-                            if (onerror) {
-                                onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
-                            }
-                            scene._removePendingData(loadingToken);
-                            return;
-                        }
-                    }
-                    catch (e) {
-                        if (onerror) {
-                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
-                        }
-                        scene._removePendingData(loadingToken);
-                        return;
-                    }
-                    if (onsuccess) {
-                        scene.importedMeshesFiles.push(rootUrl + sceneFilename);
-                        onsuccess(meshes, particleSystems, skeletons);
-                        scene._removePendingData(loadingToken);
-                    }
-                };
-                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                    // Direct load
-                    importMeshFromData(sceneFilename.substr(5));
-                    return;
-                }
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
-                    importMeshFromData(data);
-                }, progressCallBack, database);
-            };
-            if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
-                // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-            }
-            else {
-                // If the scene is a data stream or offline support is not enabled, it's a direct load
-                manifestChecked(true);
-            }
-        };
-        /**
-        * Load a scene
-        * @param rootUrl a string that defines the root url for scene and resources
-        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
-        * @param engine is the instance of BABYLON.Engine to use to create the scene
-        */
-        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
-            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
-        };
-        /**
-        * Append a scene
-        * @param rootUrl a string that defines the root url for scene and resources
-        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
-        * @param scene is the instance of BABYLON.Scene to append to
-        */
-        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
-            var database;
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            if (SceneLoader.ShowLoadingScreen) {
-                scene.getEngine().displayLoadingUI();
-            }
-            var loadSceneFromData = function (data) {
-                scene.database = database;
-                if (!plugin.load(scene, data, rootUrl)) {
-                    if (onerror) {
-                        onerror(scene);
-                    }
-                    scene._removePendingData(loadingToken);
-                    scene.getEngine().hideLoadingUI();
-                    return;
-                }
-                if (onsuccess) {
-                    onsuccess(scene);
-                }
-                scene._removePendingData(loadingToken);
-                if (SceneLoader.ShowLoadingScreen) {
-                    scene.executeWhenReady(function () {
-                        scene.getEngine().hideLoadingUI();
-                    });
-                }
-            };
-            var manifestChecked = function (success) {
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
-            };
-            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                // Direct load
-                loadSceneFromData(sceneFilename.substr(5));
-                return;
-            }
-            if (rootUrl.indexOf("file:") === -1) {
-                if (scene.getEngine().enableOfflineSupport) {
-                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-                }
-                else {
-                    manifestChecked(true);
-                }
-            }
-            else {
-                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
-            }
-        };
-        // Flags
-        SceneLoader._ForceFullSceneLoadingForIncremental = false;
-        SceneLoader._ShowLoadingScreen = true;
-        // Members
-        SceneLoader._registeredPlugins = new Array();
-        return SceneLoader;
-    })();
-    BABYLON.SceneLoader = SceneLoader;
-    ;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SceneLoader = (function () {
+        function SceneLoader() {
+        }
+        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
+            get: function () {
+                return SceneLoader._ForceFullSceneLoadingForIncremental;
+            },
+            set: function (value) {
+                SceneLoader._ForceFullSceneLoadingForIncremental = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
+            get: function () {
+                return SceneLoader._ShowLoadingScreen;
+            },
+            set: function (value) {
+                SceneLoader._ShowLoadingScreen = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SceneLoader._getPluginForFilename = function (sceneFilename) {
+            var dotPosition = sceneFilename.lastIndexOf(".");
+            var queryStringPosition = sceneFilename.indexOf("?");
+            if (queryStringPosition === -1) {
+                queryStringPosition = sceneFilename.length;
+            }
+            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
+            for (var index = 0; index < this._registeredPlugins.length; index++) {
+                var plugin = this._registeredPlugins[index];
+                if (plugin.extensions.indexOf(extension) !== -1) {
+                    return plugin;
+                }
+            }
+            return this._registeredPlugins[this._registeredPlugins.length - 1];
+        };
+        // Public functions
+        SceneLoader.GetPluginForExtension = function (extension) {
+            for (var index = 0; index < this._registeredPlugins.length; index++) {
+                var plugin = this._registeredPlugins[index];
+                if (plugin.extensions.indexOf(extension) !== -1) {
+                    return plugin;
+                }
+            }
+            return null;
+        };
+        SceneLoader.RegisterPlugin = function (plugin) {
+            plugin.extensions = plugin.extensions.toLowerCase();
+            SceneLoader._registeredPlugins.push(plugin);
+        };
+        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            var manifestChecked = function (success) {
+                scene.database = database;
+                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
+                var importMeshFromData = function (data) {
+                    var meshes = [];
+                    var particleSystems = [];
+                    var skeletons = [];
+                    try {
+                        if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
+                            if (onerror) {
+                                onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
+                            }
+                            scene._removePendingData(loadingToken);
+                            return;
+                        }
+                    }
+                    catch (e) {
+                        if (onerror) {
+                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
+                        }
+                        scene._removePendingData(loadingToken);
+                        return;
+                    }
+                    if (onsuccess) {
+                        scene.importedMeshesFiles.push(rootUrl + sceneFilename);
+                        onsuccess(meshes, particleSystems, skeletons);
+                        scene._removePendingData(loadingToken);
+                    }
+                };
+                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                    // Direct load
+                    importMeshFromData(sceneFilename.substr(5));
+                    return;
+                }
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
+                    importMeshFromData(data);
+                }, progressCallBack, database);
+            };
+            if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
+                // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+            }
+            else {
+                // If the scene is a data stream or offline support is not enabled, it's a direct load
+                manifestChecked(true);
+            }
+        };
+        /**
+        * Load a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param engine is the instance of BABYLON.Engine to use to create the scene
+        */
+        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
+            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
+        };
+        /**
+        * Append a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene is the instance of BABYLON.Scene to append to
+        */
+        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
+            var database;
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            if (SceneLoader.ShowLoadingScreen) {
+                scene.getEngine().displayLoadingUI();
+            }
+            var loadSceneFromData = function (data) {
+                scene.database = database;
+                if (!plugin.load(scene, data, rootUrl)) {
+                    if (onerror) {
+                        onerror(scene);
+                    }
+                    scene._removePendingData(loadingToken);
+                    scene.getEngine().hideLoadingUI();
+                    return;
+                }
+                if (onsuccess) {
+                    onsuccess(scene);
+                }
+                scene._removePendingData(loadingToken);
+                if (SceneLoader.ShowLoadingScreen) {
+                    scene.executeWhenReady(function () {
+                        scene.getEngine().hideLoadingUI();
+                    });
+                }
+            };
+            var manifestChecked = function (success) {
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
+            };
+            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                // Direct load
+                loadSceneFromData(sceneFilename.substr(5));
+                return;
+            }
+            if (rootUrl.indexOf("file:") === -1) {
+                if (scene.getEngine().enableOfflineSupport) {
+                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+                }
+                else {
+                    manifestChecked(true);
+                }
+            }
+            else {
+                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
+            }
+        };
+        // Flags
+        SceneLoader._ForceFullSceneLoadingForIncremental = false;
+        SceneLoader._ShowLoadingScreen = true;
+        // Members
+        SceneLoader._registeredPlugins = new Array();
+        return SceneLoader;
+    }());
+    BABYLON.SceneLoader = SceneLoader;
+    ;
+})(BABYLON || (BABYLON = {}));

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

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

+ 276 - 276
src/Materials/Textures/Procedurals/babylon.proceduralTexture.js

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

+ 138 - 138
src/Materials/Textures/babylon.baseTexture.js

@@ -1,138 +1,138 @@
-var BABYLON;
-(function (BABYLON) {
-    var BaseTexture = (function () {
-        function BaseTexture(scene) {
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
-            this.hasAlpha = false;
-            this.getAlphaFromRGB = false;
-            this.level = 1;
-            this.isCube = false;
-            this.isRenderTarget = false;
-            this.animations = new Array();
-            this.coordinatesIndex = 0;
-            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
-            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.anisotropicFilteringLevel = 4;
-            this._scene = scene;
-            this._scene.textures.push(this);
-        }
-        BaseTexture.prototype.getScene = function () {
-            return this._scene;
-        };
-        BaseTexture.prototype.getTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getReflectionTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getInternalTexture = function () {
-            return this._texture;
-        };
-        BaseTexture.prototype.isReady = function () {
-            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return true;
-            }
-            if (this._texture) {
-                return this._texture.isReady;
-            }
-            return false;
-        };
-        BaseTexture.prototype.getSize = function () {
-            if (this._texture._width) {
-                return { width: this._texture._width, height: this._texture._height };
-            }
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: 0, height: 0 };
-        };
-        BaseTexture.prototype.getBaseSize = function () {
-            if (!this.isReady())
-                return { width: 0, height: 0 };
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
-        };
-        BaseTexture.prototype.scale = function (ratio) {
-        };
-        Object.defineProperty(BaseTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    texturesCache.splice(index, 1);
-                    return;
-                }
-            }
-        };
-        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
-                        texturesCacheEntry.references++;
-                        return texturesCacheEntry;
-                    }
-                }
-            }
-            return null;
-        };
-        BaseTexture.prototype.delayLoad = function () {
-        };
-        BaseTexture.prototype.clone = function () {
-            return null;
-        };
-        BaseTexture.prototype.releaseInternalTexture = function () {
-            if (this._texture) {
-                this._scene.getEngine().releaseInternalTexture(this._texture);
-                delete this._texture;
-            }
-        };
-        BaseTexture.prototype.dispose = function () {
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            var index = this._scene.textures.indexOf(this);
-            if (index >= 0) {
-                this._scene.textures.splice(index, 1);
-            }
-            if (this._texture === undefined) {
-                return;
-            }
-            // Release
-            this.releaseInternalTexture();
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        BaseTexture.prototype.serialize = function () {
-            var serializationObject = {};
-            if (!this.name) {
-                return null;
-            }
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.level = this.level;
-            serializationObject.coordinatesIndex = this.coordinatesIndex;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            serializationObject.wrapU = this.wrapU;
-            serializationObject.wrapV = this.wrapV;
-            // Animations
-            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
-            return serializationObject;
-        };
-        return BaseTexture;
-    })();
-    BABYLON.BaseTexture = BaseTexture;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var BaseTexture = (function () {
+        function BaseTexture(scene) {
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
+            this.hasAlpha = false;
+            this.getAlphaFromRGB = false;
+            this.level = 1;
+            this.isCube = false;
+            this.isRenderTarget = false;
+            this.animations = new Array();
+            this.coordinatesIndex = 0;
+            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
+            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.anisotropicFilteringLevel = 4;
+            this._scene = scene;
+            this._scene.textures.push(this);
+        }
+        BaseTexture.prototype.getScene = function () {
+            return this._scene;
+        };
+        BaseTexture.prototype.getTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getReflectionTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getInternalTexture = function () {
+            return this._texture;
+        };
+        BaseTexture.prototype.isReady = function () {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return true;
+            }
+            if (this._texture) {
+                return this._texture.isReady;
+            }
+            return false;
+        };
+        BaseTexture.prototype.getSize = function () {
+            if (this._texture._width) {
+                return { width: this._texture._width, height: this._texture._height };
+            }
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: 0, height: 0 };
+        };
+        BaseTexture.prototype.getBaseSize = function () {
+            if (!this.isReady())
+                return { width: 0, height: 0 };
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
+        };
+        BaseTexture.prototype.scale = function (ratio) {
+        };
+        Object.defineProperty(BaseTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    texturesCache.splice(index, 1);
+                    return;
+                }
+            }
+        };
+        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
+                        texturesCacheEntry.references++;
+                        return texturesCacheEntry;
+                    }
+                }
+            }
+            return null;
+        };
+        BaseTexture.prototype.delayLoad = function () {
+        };
+        BaseTexture.prototype.clone = function () {
+            return null;
+        };
+        BaseTexture.prototype.releaseInternalTexture = function () {
+            if (this._texture) {
+                this._scene.getEngine().releaseInternalTexture(this._texture);
+                delete this._texture;
+            }
+        };
+        BaseTexture.prototype.dispose = function () {
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            var index = this._scene.textures.indexOf(this);
+            if (index >= 0) {
+                this._scene.textures.splice(index, 1);
+            }
+            if (this._texture === undefined) {
+                return;
+            }
+            // Release
+            this.releaseInternalTexture();
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        BaseTexture.prototype.serialize = function () {
+            var serializationObject = {};
+            if (!this.name) {
+                return null;
+            }
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.level = this.level;
+            serializationObject.coordinatesIndex = this.coordinatesIndex;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            serializationObject.wrapU = this.wrapU;
+            serializationObject.wrapV = this.wrapV;
+            // Animations
+            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
+            return serializationObject;
+        };
+        return BaseTexture;
+    }());
+    BABYLON.BaseTexture = BaseTexture;
+})(BABYLON || (BABYLON = {}));

+ 96 - 96
src/Materials/Textures/babylon.cubeTexture.js

@@ -1,96 +1,96 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var CubeTexture = (function (_super) {
-        __extends(CubeTexture, _super);
-        function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
-            _super.call(this, scene);
-            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-            this.name = rootUrl;
-            this.url = rootUrl;
-            this._noMipmap = noMipmap;
-            this.hasAlpha = false;
-            if (!rootUrl && !files) {
-                return;
-            }
-            this._texture = this._getFromCache(rootUrl, noMipmap);
-            if (!files) {
-                if (!extensions) {
-                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
-                }
-                files = [];
-                for (var index = 0; index < extensions.length; index++) {
-                    files.push(rootUrl + extensions[index]);
-                }
-                this._extensions = extensions;
-            }
-            this._files = files;
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-            this.isCube = true;
-            this._textureMatrix = BABYLON.Matrix.Identity();
-        }
-        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
-            return new CubeTexture("", scene, null, noMipmap, files);
-        };
-        CubeTexture.prototype.clone = function () {
-            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
-            // Base texture
-            newTexture.level = this.level;
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            newTexture.coordinatesIndex = this.coordinatesIndex;
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        // Methods
-        CubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
-            }
-        };
-        CubeTexture.prototype.getReflectionTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        };
-        CubeTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.isCube = true;
-            serializationObject.level = this.level;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            return serializationObject;
-        };
-        return CubeTexture;
-    })(BABYLON.BaseTexture);
-    BABYLON.CubeTexture = CubeTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var CubeTexture = (function (_super) {
+        __extends(CubeTexture, _super);
+        function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
+            _super.call(this, scene);
+            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+            this.name = rootUrl;
+            this.url = rootUrl;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+            if (!rootUrl && !files) {
+                return;
+            }
+            this._texture = this._getFromCache(rootUrl, noMipmap);
+            if (!files) {
+                if (!extensions) {
+                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
+                }
+                files = [];
+                for (var index = 0; index < extensions.length; index++) {
+                    files.push(rootUrl + extensions[index]);
+                }
+                this._extensions = extensions;
+            }
+            this._files = files;
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+            this.isCube = true;
+            this._textureMatrix = BABYLON.Matrix.Identity();
+        }
+        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
+            return new CubeTexture("", scene, null, noMipmap, files);
+        };
+        CubeTexture.prototype.clone = function () {
+            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
+            // Base texture
+            newTexture.level = this.level;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        // Methods
+        CubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
+            }
+        };
+        CubeTexture.prototype.getReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
+                texture.name = parsedTexture.name;
+                texture.hasAlpha = parsedTexture.hasAlpha;
+                texture.level = parsedTexture.level;
+                texture.coordinatesMode = parsedTexture.coordinatesMode;
+            }
+            return texture;
+        };
+        CubeTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.isCube = true;
+            serializationObject.level = this.level;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            return serializationObject;
+        };
+        return CubeTexture;
+    }(BABYLON.BaseTexture));
+    BABYLON.CubeTexture = CubeTexture;
+})(BABYLON || (BABYLON = {}));

+ 93 - 93
src/Materials/Textures/babylon.dynamicTexture.js

@@ -1,93 +1,93 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var DynamicTexture = (function (_super) {
-        __extends(DynamicTexture, _super);
-        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.name = name;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._generateMipMaps = generateMipMaps;
-            if (options.getContext) {
-                this._canvas = options;
-                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
-            }
-            else {
-                this._canvas = document.createElement("canvas");
-                if (options.width) {
-                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
-                }
-                else {
-                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
-                }
-            }
-            var textureSize = this.getSize();
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this._context = this._canvas.getContext("2d");
-        }
-        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        DynamicTexture.prototype.scale = function (ratio) {
-            var textureSize = this.getSize();
-            textureSize.width *= ratio;
-            textureSize.height *= ratio;
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this.releaseInternalTexture();
-            this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
-        };
-        DynamicTexture.prototype.getContext = function () {
-            return this._context;
-        };
-        DynamicTexture.prototype.clear = function () {
-            var size = this.getSize();
-            this._context.fillRect(0, 0, size.width, size.height);
-        };
-        DynamicTexture.prototype.update = function (invertY) {
-            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
-        };
-        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
-            if (update === void 0) { update = true; }
-            var size = this.getSize();
-            if (clearColor) {
-                this._context.fillStyle = clearColor;
-                this._context.fillRect(0, 0, size.width, size.height);
-            }
-            this._context.font = font;
-            if (x === null) {
-                var textSize = this._context.measureText(text);
-                x = (size.width - textSize.width) / 2;
-            }
-            this._context.fillStyle = color;
-            this._context.fillText(text, x, y);
-            if (update) {
-                this.update(invertY);
-            }
-        };
-        DynamicTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // Dynamic Texture
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            return newTexture;
-        };
-        return DynamicTexture;
-    })(BABYLON.Texture);
-    BABYLON.DynamicTexture = DynamicTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var DynamicTexture = (function (_super) {
+        __extends(DynamicTexture, _super);
+        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.name = name;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._generateMipMaps = generateMipMaps;
+            if (options.getContext) {
+                this._canvas = options;
+                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
+            }
+            else {
+                this._canvas = document.createElement("canvas");
+                if (options.width) {
+                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
+                }
+                else {
+                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
+                }
+            }
+            var textureSize = this.getSize();
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+        }
+        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        DynamicTexture.prototype.scale = function (ratio) {
+            var textureSize = this.getSize();
+            textureSize.width *= ratio;
+            textureSize.height *= ratio;
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
+        };
+        DynamicTexture.prototype.getContext = function () {
+            return this._context;
+        };
+        DynamicTexture.prototype.clear = function () {
+            var size = this.getSize();
+            this._context.fillRect(0, 0, size.width, size.height);
+        };
+        DynamicTexture.prototype.update = function (invertY) {
+            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
+        };
+        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
+            if (update === void 0) { update = true; }
+            var size = this.getSize();
+            if (clearColor) {
+                this._context.fillStyle = clearColor;
+                this._context.fillRect(0, 0, size.width, size.height);
+            }
+            this._context.font = font;
+            if (x === null) {
+                var textSize = this._context.measureText(text);
+                x = (size.width - textSize.width) / 2;
+            }
+            this._context.fillStyle = color;
+            this._context.fillText(text, x, y);
+            if (update) {
+                this.update(invertY);
+            }
+        };
+        DynamicTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // Dynamic Texture
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            return newTexture;
+        };
+        return DynamicTexture;
+    }(BABYLON.Texture));
+    BABYLON.DynamicTexture = DynamicTexture;
+})(BABYLON || (BABYLON = {}));

+ 162 - 162
src/Materials/Textures/babylon.hdrCubeTexture.js

@@ -1,162 +1,162 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var HDRCubeTexture = (function (_super) {
-        __extends(HDRCubeTexture, _super);
-        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
-            if (noMipmap === void 0) { noMipmap = false; }
-            if (generateHarmonics === void 0) { generateHarmonics = true; }
-            if (useInGammaSpace === void 0) { useInGammaSpace = false; }
-            if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
-            _super.call(this, scene);
-            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-            this._useInGammaSpace = false;
-            this._generateHarmonics = true;
-            this.sphericalPolynomial = null;
-            this.isPMREM = false;
-            this.name = url;
-            this.url = url;
-            this._noMipmap = noMipmap;
-            this.hasAlpha = false;
-            this._size = size;
-            this._useInGammaSpace = useInGammaSpace;
-            this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
-            this.isPMREM = this._usePMREMGenerator;
-            if (!url) {
-                return;
-            }
-            this._texture = this._getFromCache(url, noMipmap);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this.loadTexture();
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-            this.isCube = true;
-            this._textureMatrix = BABYLON.Matrix.Identity();
-        }
-        HDRCubeTexture.prototype.loadTexture = function () {
-            var _this = this;
-            var callback = function (buffer) {
-                // Extract the raw linear data.
-                var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
-                // Generate harmonics if needed.
-                if (_this._generateHarmonics) {
-                    _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
-                }
-                var results = [];
-                var byteArray = null;
-                // Create uintarray fallback.
-                if (!_this.getScene().getEngine().getCaps().textureFloat) {
-                    // 3 channels of 1 bytes per pixel in bytes.
-                    var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
-                    byteArray = new Uint8Array(byteBuffer);
-                }
-                // Push each faces.
-                for (var j = 0; j < 6; j++) {
-                    var dataFace = data[HDRCubeTexture._facesMapping[j]];
-                    // If special cases.
-                    if (_this._useInGammaSpace || byteArray) {
-                        for (var i = 0; i < _this._size * _this._size; i++) {
-                            // Put in gamma space if requested.
-                            if (_this._useInGammaSpace) {
-                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
-                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
-                            }
-                            // Convert to int texture for fallback.
-                            if (byteArray) {
-                                // R
-                                byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
-                                byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
-                                // G
-                                byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
-                                byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
-                                // B
-                                byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
-                                byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
-                            }
-                        }
-                    }
-                    results.push(dataFace);
-                }
-                return results;
-            };
-            var mipmapGenerator = null;
-            if (!this._noMipmap && this._usePMREMGenerator) {
-                mipmapGenerator = function (data) {
-                    var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
-                    return generator.filterCubeMap();
-                };
-            }
-            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
-        };
-        HDRCubeTexture.prototype.clone = function () {
-            var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
-            // Base texture
-            newTexture.level = this.level;
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            newTexture.coordinatesIndex = this.coordinatesIndex;
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        // Methods
-        HDRCubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-            if (!this._texture) {
-                this.loadTexture();
-            }
-        };
-        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        };
-        HDRCubeTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.isCube = true;
-            serializationObject.level = this.level;
-            serializationObject.size = this._size;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            serializationObject.useInGammaSpace = this._useInGammaSpace;
-            serializationObject.generateHarmonics = this._generateHarmonics;
-            serializationObject.usePMREMGenerator = this._usePMREMGenerator;
-            return serializationObject;
-        };
-        HDRCubeTexture._facesMapping = [
-            "right",
-            "up",
-            "front",
-            "left",
-            "down",
-            "back"
-        ];
-        return HDRCubeTexture;
-    })(BABYLON.BaseTexture);
-    BABYLON.HDRCubeTexture = HDRCubeTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var HDRCubeTexture = (function (_super) {
+        __extends(HDRCubeTexture, _super);
+        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
+            if (noMipmap === void 0) { noMipmap = false; }
+            if (generateHarmonics === void 0) { generateHarmonics = true; }
+            if (useInGammaSpace === void 0) { useInGammaSpace = false; }
+            if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
+            _super.call(this, scene);
+            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+            this._useInGammaSpace = false;
+            this._generateHarmonics = true;
+            this.sphericalPolynomial = null;
+            this.isPMREM = false;
+            this.name = url;
+            this.url = url;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+            this._size = size;
+            this._useInGammaSpace = useInGammaSpace;
+            this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
+            this.isPMREM = this._usePMREMGenerator;
+            if (!url) {
+                return;
+            }
+            this._texture = this._getFromCache(url, noMipmap);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this.loadTexture();
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+            this.isCube = true;
+            this._textureMatrix = BABYLON.Matrix.Identity();
+        }
+        HDRCubeTexture.prototype.loadTexture = function () {
+            var _this = this;
+            var callback = function (buffer) {
+                // Extract the raw linear data.
+                var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
+                // Generate harmonics if needed.
+                if (_this._generateHarmonics) {
+                    _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
+                }
+                var results = [];
+                var byteArray = null;
+                // Create uintarray fallback.
+                if (!_this.getScene().getEngine().getCaps().textureFloat) {
+                    // 3 channels of 1 bytes per pixel in bytes.
+                    var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
+                    byteArray = new Uint8Array(byteBuffer);
+                }
+                // Push each faces.
+                for (var j = 0; j < 6; j++) {
+                    var dataFace = data[HDRCubeTexture._facesMapping[j]];
+                    // If special cases.
+                    if (_this._useInGammaSpace || byteArray) {
+                        for (var i = 0; i < _this._size * _this._size; i++) {
+                            // Put in gamma space if requested.
+                            if (_this._useInGammaSpace) {
+                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
+                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
+                            }
+                            // Convert to int texture for fallback.
+                            if (byteArray) {
+                                // R
+                                byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
+                                byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
+                                // G
+                                byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
+                                byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
+                                // B
+                                byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
+                                byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
+                            }
+                        }
+                    }
+                    results.push(dataFace);
+                }
+                return results;
+            };
+            var mipmapGenerator = null;
+            if (!this._noMipmap && this._usePMREMGenerator) {
+                mipmapGenerator = function (data) {
+                    var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
+                    return generator.filterCubeMap();
+                };
+            }
+            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
+        };
+        HDRCubeTexture.prototype.clone = function () {
+            var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
+            // Base texture
+            newTexture.level = this.level;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        // Methods
+        HDRCubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+            if (!this._texture) {
+                this.loadTexture();
+            }
+        };
+        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
+                texture.name = parsedTexture.name;
+                texture.hasAlpha = parsedTexture.hasAlpha;
+                texture.level = parsedTexture.level;
+                texture.coordinatesMode = parsedTexture.coordinatesMode;
+            }
+            return texture;
+        };
+        HDRCubeTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.isCube = true;
+            serializationObject.level = this.level;
+            serializationObject.size = this._size;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            serializationObject.useInGammaSpace = this._useInGammaSpace;
+            serializationObject.generateHarmonics = this._generateHarmonics;
+            serializationObject.usePMREMGenerator = this._usePMREMGenerator;
+            return serializationObject;
+        };
+        HDRCubeTexture._facesMapping = [
+            "right",
+            "up",
+            "front",
+            "left",
+            "down",
+            "back"
+        ];
+        return HDRCubeTexture;
+    }(BABYLON.BaseTexture));
+    BABYLON.HDRCubeTexture = HDRCubeTexture;
+})(BABYLON || (BABYLON = {}));

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

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

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

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

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

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

+ 254 - 254
src/Materials/Textures/babylon.renderTargetTexture.js

@@ -1,254 +1,254 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var RenderTargetTexture = (function (_super) {
-        __extends(RenderTargetTexture, _super);
-        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
-            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
-            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
-            if (isCube === void 0) { isCube = false; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.isCube = isCube;
-            this.renderList = new Array();
-            this.renderParticles = true;
-            this.renderSprites = false;
-            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
-            this._currentRefreshId = -1;
-            this._refreshRate = 1;
-            this.name = name;
-            this.isRenderTarget = true;
-            this._size = size;
-            this._generateMipMaps = generateMipMaps;
-            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
-            if (isCube) {
-                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
-                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
-                this._textureMatrix = BABYLON.Matrix.Identity();
-            }
-            else {
-                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
-            }
-            // Rendering groups
-            this._renderingManager = new BABYLON.RenderingManager(scene);
-        }
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.resetRefreshCounter = function () {
-            this._currentRefreshId = -1;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
-            get: function () {
-                return this._refreshRate;
-            },
-            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
-            set: function (value) {
-                this._refreshRate = value;
-                this.resetRefreshCounter();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype._shouldRender = function () {
-            if (this._currentRefreshId === -1) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            if (this.refreshRate === this._currentRefreshId) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            this._currentRefreshId++;
-            return false;
-        };
-        RenderTargetTexture.prototype.isReady = function () {
-            if (!this.getScene().renderTargetsEnabled) {
-                return false;
-            }
-            return _super.prototype.isReady.call(this);
-        };
-        RenderTargetTexture.prototype.getRenderSize = function () {
-            return this._size;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.scale = function (ratio) {
-            var newSize = this._size * ratio;
-            this.resize(newSize, this._generateMipMaps);
-        };
-        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
-            if (this.isCube) {
-                return this._textureMatrix;
-            }
-            return _super.prototype.getReflectionTextureMatrix.call(this);
-        };
-        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
-            this.releaseInternalTexture();
-            if (this.isCube) {
-                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
-            }
-            else {
-                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
-            }
-        };
-        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
-            }
-            if (this._waitingRenderList) {
-                this.renderList = [];
-                for (var index = 0; index < this._waitingRenderList.length; index++) {
-                    var id = this._waitingRenderList[index];
-                    this.renderList.push(scene.getMeshByID(id));
-                }
-                delete this._waitingRenderList;
-            }
-            if (this.renderList && this.renderList.length === 0) {
-                return;
-            }
-            // Prepare renderingManager
-            this._renderingManager.reset();
-            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
-            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
-                var mesh = currentRenderList[meshIndex];
-                if (mesh) {
-                    if (!mesh.isReady()) {
-                        // Reset _currentRefreshId
-                        this.resetRefreshCounter();
-                        continue;
-                    }
-                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
-                        mesh._activate(scene.getRenderId());
-                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                            var subMesh = mesh.subMeshes[subIndex];
-                            scene._activeIndices += subMesh.indexCount;
-                            this._renderingManager.dispatch(subMesh);
-                        }
-                    }
-                }
-            }
-            if (this.isCube) {
-                for (var face = 0; face < 6; face++) {
-                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
-                    scene.incrementRenderId();
-                }
-            }
-            else {
-                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
-            }
-            if (this.onAfterUnbind) {
-                this.onAfterUnbind();
-            }
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
-            }
-            scene.resetCachedMaterial();
-        };
-        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            // Bind
-            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
-                if (this.isCube) {
-                    engine.bindFramebuffer(this._texture, faceIndex);
-                }
-                else {
-                    engine.bindFramebuffer(this._texture);
-                }
-            }
-            if (this.onBeforeRender) {
-                this.onBeforeRender(faceIndex);
-            }
-            // Clear
-            if (this.onClear) {
-                this.onClear(engine);
-            }
-            else {
-                engine.clear(scene.clearColor, true, true);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            // Render
-            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
-            if (useCameraPostProcess) {
-                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            if (this.onAfterRender) {
-                this.onAfterRender(faceIndex);
-            }
-            // Dump ?
-            if (dumpForDebug) {
-                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
-            }
-            // Unbind
-            if (!this.isCube || faceIndex === 5) {
-                if (this.isCube) {
-                    if (faceIndex === 5) {
-                        engine.generateMipMapsForCubemap(this._texture);
-                    }
-                }
-                engine.unBindFramebuffer(this._texture, this.isCube);
-            }
-        };
-        RenderTargetTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // RenderTarget Texture
-            newTexture.coordinatesMode = this.coordinatesMode;
-            newTexture.renderList = this.renderList.slice(0);
-            return newTexture;
-        };
-        RenderTargetTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.renderTargetSize = this.getRenderSize();
-            serializationObject.renderList = [];
-            for (var index = 0; index < this.renderList.length; index++) {
-                serializationObject.renderList.push(this.renderList[index].id);
-            }
-            return serializationObject;
-        };
-        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
-        return RenderTargetTexture;
-    })(BABYLON.Texture);
-    BABYLON.RenderTargetTexture = RenderTargetTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var RenderTargetTexture = (function (_super) {
+        __extends(RenderTargetTexture, _super);
+        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
+            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
+            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
+            if (isCube === void 0) { isCube = false; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.isCube = isCube;
+            this.renderList = new Array();
+            this.renderParticles = true;
+            this.renderSprites = false;
+            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
+            this._currentRefreshId = -1;
+            this._refreshRate = 1;
+            this.name = name;
+            this.isRenderTarget = true;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
+            if (isCube) {
+                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
+                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
+                this._textureMatrix = BABYLON.Matrix.Identity();
+            }
+            else {
+                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
+            }
+            // Rendering groups
+            this._renderingManager = new BABYLON.RenderingManager(scene);
+        }
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.resetRefreshCounter = function () {
+            this._currentRefreshId = -1;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
+            get: function () {
+                return this._refreshRate;
+            },
+            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+            set: function (value) {
+                this._refreshRate = value;
+                this.resetRefreshCounter();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype._shouldRender = function () {
+            if (this._currentRefreshId === -1) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            if (this.refreshRate === this._currentRefreshId) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            this._currentRefreshId++;
+            return false;
+        };
+        RenderTargetTexture.prototype.isReady = function () {
+            if (!this.getScene().renderTargetsEnabled) {
+                return false;
+            }
+            return _super.prototype.isReady.call(this);
+        };
+        RenderTargetTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.scale = function (ratio) {
+            var newSize = this._size * ratio;
+            this.resize(newSize, this._generateMipMaps);
+        };
+        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
+            if (this.isCube) {
+                return this._textureMatrix;
+            }
+            return _super.prototype.getReflectionTextureMatrix.call(this);
+        };
+        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
+            this.releaseInternalTexture();
+            if (this.isCube) {
+                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
+            }
+            else {
+                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+            }
+        };
+        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
+            }
+            if (this._waitingRenderList) {
+                this.renderList = [];
+                for (var index = 0; index < this._waitingRenderList.length; index++) {
+                    var id = this._waitingRenderList[index];
+                    this.renderList.push(scene.getMeshByID(id));
+                }
+                delete this._waitingRenderList;
+            }
+            if (this.renderList && this.renderList.length === 0) {
+                return;
+            }
+            // Prepare renderingManager
+            this._renderingManager.reset();
+            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
+            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
+                var mesh = currentRenderList[meshIndex];
+                if (mesh) {
+                    if (!mesh.isReady()) {
+                        // Reset _currentRefreshId
+                        this.resetRefreshCounter();
+                        continue;
+                    }
+                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
+                        mesh._activate(scene.getRenderId());
+                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                            var subMesh = mesh.subMeshes[subIndex];
+                            scene._activeIndices += subMesh.indexCount;
+                            this._renderingManager.dispatch(subMesh);
+                        }
+                    }
+                }
+            }
+            if (this.isCube) {
+                for (var face = 0; face < 6; face++) {
+                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
+                    scene.incrementRenderId();
+                }
+            }
+            else {
+                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
+            }
+            if (this.onAfterUnbind) {
+                this.onAfterUnbind();
+            }
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
+            }
+            scene.resetCachedMaterial();
+        };
+        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            // Bind
+            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
+                if (this.isCube) {
+                    engine.bindFramebuffer(this._texture, faceIndex);
+                }
+                else {
+                    engine.bindFramebuffer(this._texture);
+                }
+            }
+            if (this.onBeforeRender) {
+                this.onBeforeRender(faceIndex);
+            }
+            // Clear
+            if (this.onClear) {
+                this.onClear(engine);
+            }
+            else {
+                engine.clear(scene.clearColor, true, true);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            // Render
+            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
+            if (useCameraPostProcess) {
+                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            if (this.onAfterRender) {
+                this.onAfterRender(faceIndex);
+            }
+            // Dump ?
+            if (dumpForDebug) {
+                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
+            }
+            // Unbind
+            if (!this.isCube || faceIndex === 5) {
+                if (this.isCube) {
+                    if (faceIndex === 5) {
+                        engine.generateMipMapsForCubemap(this._texture);
+                    }
+                }
+                engine.unBindFramebuffer(this._texture, this.isCube);
+            }
+        };
+        RenderTargetTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // RenderTarget Texture
+            newTexture.coordinatesMode = this.coordinatesMode;
+            newTexture.renderList = this.renderList.slice(0);
+            return newTexture;
+        };
+        RenderTargetTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.renderTargetSize = this.getRenderSize();
+            serializationObject.renderList = [];
+            for (var index = 0; index < this.renderList.length; index++) {
+                serializationObject.renderList.push(this.renderList[index].id);
+            }
+            return serializationObject;
+        };
+        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
+        return RenderTargetTexture;
+    }(BABYLON.Texture));
+    BABYLON.RenderTargetTexture = RenderTargetTexture;
+})(BABYLON || (BABYLON = {}));

+ 274 - 274
src/Materials/Textures/babylon.texture.js

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

+ 58 - 58
src/Materials/Textures/babylon.videoTexture.js

@@ -1,58 +1,58 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var VideoTexture = (function (_super) {
-        __extends(VideoTexture, _super);
-        function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
-            var _this = this;
-            if (generateMipMaps === void 0) { generateMipMaps = false; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps, invertY);
-            this._autoLaunch = true;
-            this.name = name;
-            this.video = document.createElement("video");
-            this.video.autoplay = false;
-            this.video.loop = true;
-            this.video.addEventListener("canplaythrough", function () {
-                if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
-                    _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-                    _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-                }
-                else {
-                    _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    generateMipMaps = false;
-                }
-                _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
-                _this._texture.isReady = true;
-            });
-            urls.forEach(function (url) {
-                //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
-                var source = document.createElement("source");
-                source.src = url;
-                _this.video.appendChild(source);
-            });
-            this._lastUpdate = BABYLON.Tools.Now;
-        }
-        VideoTexture.prototype.update = function () {
-            if (this._autoLaunch) {
-                this._autoLaunch = false;
-                this.video.play();
-            }
-            var now = BABYLON.Tools.Now;
-            if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
-                return false;
-            }
-            this._lastUpdate = now;
-            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
-            return true;
-        };
-        return VideoTexture;
-    })(BABYLON.Texture);
-    BABYLON.VideoTexture = VideoTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var VideoTexture = (function (_super) {
+        __extends(VideoTexture, _super);
+        function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
+            var _this = this;
+            if (generateMipMaps === void 0) { generateMipMaps = false; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps, invertY);
+            this._autoLaunch = true;
+            this.name = name;
+            this.video = document.createElement("video");
+            this.video.autoplay = false;
+            this.video.loop = true;
+            this.video.addEventListener("canplaythrough", function () {
+                if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
+                    _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+                    _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+                }
+                else {
+                    _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    generateMipMaps = false;
+                }
+                _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
+                _this._texture.isReady = true;
+            });
+            urls.forEach(function (url) {
+                //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
+                var source = document.createElement("source");
+                source.src = url;
+                _this.video.appendChild(source);
+            });
+            this._lastUpdate = BABYLON.Tools.Now;
+        }
+        VideoTexture.prototype.update = function () {
+            if (this._autoLaunch) {
+                this._autoLaunch = false;
+                this.video.play();
+            }
+            var now = BABYLON.Tools.Now;
+            if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
+                return false;
+            }
+            this._lastUpdate = now;
+            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
+            return true;
+        };
+        return VideoTexture;
+    }(BABYLON.Texture));
+    BABYLON.VideoTexture = VideoTexture;
+})(BABYLON || (BABYLON = {}));

+ 453 - 453
src/Materials/babylon.effect.js

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

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

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

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

@@ -1,318 +1,318 @@
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var MaterialDefines = (function () {
-        function MaterialDefines() {
-        }
-        MaterialDefines.prototype.isEqual = function (other) {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (this[prop] !== other[prop]) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        MaterialDefines.prototype.cloneTo = function (other) {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                other[prop] = this[prop];
-            }
-        };
-        MaterialDefines.prototype.reset = function () {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (typeof (this[prop]) === "number") {
-                    this[prop] = 0;
-                }
-                else {
-                    this[prop] = false;
-                }
-            }
-        };
-        MaterialDefines.prototype.toString = function () {
-            var result = "";
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (typeof (this[prop]) === "number") {
-                    result += "#define " + prop + " " + this[prop] + "\n";
-                }
-                else if (this[prop]) {
-                    result += "#define " + prop + "\n";
-                }
-            }
-            return result;
-        };
-        return MaterialDefines;
-    })();
-    BABYLON.MaterialDefines = MaterialDefines;
-    var Material = (function () {
-        function Material(name, scene, doNotAdd) {
-            this.name = name;
-            this.checkReadyOnEveryCall = false;
-            this.checkReadyOnlyOnce = false;
-            this.state = "";
-            this.alpha = 1.0;
-            this.backFaceCulling = true;
-            this.sideOrientation = Material.CounterClockWiseSideOrientation;
-            this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
-            this.disableDepthWrite = false;
-            this.fogEnabled = true;
-            this.pointSize = 1.0;
-            this.zOffset = 0;
-            this._wasPreviouslyReady = false;
-            this._fillMode = Material.TriangleFillMode;
-            this.id = name;
-            this._scene = scene;
-            if (!doNotAdd) {
-                scene.materials.push(this);
-            }
-        }
-        Object.defineProperty(Material, "TriangleFillMode", {
-            get: function () {
-                return Material._TriangleFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "WireFrameFillMode", {
-            get: function () {
-                return Material._WireFrameFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "PointFillMode", {
-            get: function () {
-                return Material._PointFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "ClockWiseSideOrientation", {
-            get: function () {
-                return Material._ClockWiseSideOrientation;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
-            get: function () {
-                return Material._CounterClockWiseSideOrientation;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "wireframe", {
-            get: function () {
-                return this._fillMode === Material.WireFrameFillMode;
-            },
-            set: function (value) {
-                this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "pointsCloud", {
-            get: function () {
-                return this._fillMode === Material.PointFillMode;
-            },
-            set: function (value) {
-                this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "fillMode", {
-            get: function () {
-                return this._fillMode;
-            },
-            set: function (value) {
-                this._fillMode = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "isFrozen", {
-            get: function () {
-                return this.checkReadyOnlyOnce;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Material.prototype.freeze = function () {
-            this.checkReadyOnlyOnce = true;
-        };
-        Material.prototype.unfreeze = function () {
-            this.checkReadyOnlyOnce = false;
-        };
-        Material.prototype.isReady = function (mesh, useInstances) {
-            return true;
-        };
-        Material.prototype.getEffect = function () {
-            return this._effect;
-        };
-        Material.prototype.getScene = function () {
-            return this._scene;
-        };
-        Material.prototype.needAlphaBlending = function () {
-            return (this.alpha < 1.0);
-        };
-        Material.prototype.needAlphaTesting = function () {
-            return false;
-        };
-        Material.prototype.getAlphaTestTexture = function () {
-            return null;
-        };
-        Material.prototype.trackCreation = function (onCompiled, onError) {
-        };
-        Material.prototype.markDirty = function () {
-            this._wasPreviouslyReady = false;
-        };
-        Material.prototype._preBind = function () {
-            var engine = this._scene.getEngine();
-            engine.enableEffect(this._effect);
-            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
-        };
-        Material.prototype.bind = function (world, mesh) {
-            this._scene._cachedMaterial = this;
-            if (this.onBind) {
-                this.onBind(this, mesh);
-            }
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                this._cachedDepthWriteState = engine.getDepthWrite();
-                engine.setDepthWrite(false);
-            }
-        };
-        Material.prototype.bindOnlyWorldMatrix = function (world) {
-        };
-        Material.prototype.unbind = function () {
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                engine.setDepthWrite(this._cachedDepthWriteState);
-            }
-        };
-        Material.prototype.clone = function (name) {
-            return null;
-        };
-        Material.prototype.getBindedMeshes = function () {
-            var result = new Array();
-            for (var index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.material === this) {
-                    result.push(mesh);
-                }
-            }
-            return result;
-        };
-        Material.prototype.dispose = function (forceDisposeEffect) {
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            var index = this._scene.materials.indexOf(this);
-            if (index >= 0) {
-                this._scene.materials.splice(index, 1);
-            }
-            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
-            if (forceDisposeEffect && this._effect) {
-                this._scene.getEngine()._releaseEffect(this._effect);
-                this._effect = null;
-            }
-            // Remove from meshes
-            for (index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.material === this) {
-                    mesh.material = null;
-                }
-            }
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        Material.prototype.serialize = function () {
-            return BABYLON.SerializationHelper.Serialize(this);
-        };
-        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
-            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
-            multiMaterial.id = parsedMultiMaterial.id;
-            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
-            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
-                var subMatId = parsedMultiMaterial.materials[matIndex];
-                if (subMatId) {
-                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
-                }
-                else {
-                    multiMaterial.subMaterials.push(null);
-                }
-            }
-            return multiMaterial;
-        };
-        Material.Parse = function (parsedMaterial, scene, rootUrl) {
-            if (!parsedMaterial.customType) {
-                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
-            }
-            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
-            return materialType.Parse(parsedMaterial, scene, rootUrl);
-            ;
-        };
-        Material._TriangleFillMode = 0;
-        Material._WireFrameFillMode = 1;
-        Material._PointFillMode = 2;
-        Material._ClockWiseSideOrientation = 0;
-        Material._CounterClockWiseSideOrientation = 1;
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "id", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "checkReadyOnEveryCall", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "checkReadyOnlyOnce", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "state", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "alpha", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "backFaceCulling", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "sideOrientation", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "alphaMode", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "disableDepthWrite", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "fogEnabled", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "pointSize", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "zOffset", void 0);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "wireframe", null);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "pointsCloud", null);
-        __decorate([
-            BABYLON.serialize()
-        ], Material.prototype, "fillMode", null);
-        return Material;
-    })();
-    BABYLON.Material = Material;
-})(BABYLON || (BABYLON = {}));
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var MaterialDefines = (function () {
+        function MaterialDefines() {
+        }
+        MaterialDefines.prototype.isEqual = function (other) {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (this[prop] !== other[prop]) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        MaterialDefines.prototype.cloneTo = function (other) {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                other[prop] = this[prop];
+            }
+        };
+        MaterialDefines.prototype.reset = function () {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (typeof (this[prop]) === "number") {
+                    this[prop] = 0;
+                }
+                else {
+                    this[prop] = false;
+                }
+            }
+        };
+        MaterialDefines.prototype.toString = function () {
+            var result = "";
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (typeof (this[prop]) === "number") {
+                    result += "#define " + prop + " " + this[prop] + "\n";
+                }
+                else if (this[prop]) {
+                    result += "#define " + prop + "\n";
+                }
+            }
+            return result;
+        };
+        return MaterialDefines;
+    }());
+    BABYLON.MaterialDefines = MaterialDefines;
+    var Material = (function () {
+        function Material(name, scene, doNotAdd) {
+            this.name = name;
+            this.checkReadyOnEveryCall = false;
+            this.checkReadyOnlyOnce = false;
+            this.state = "";
+            this.alpha = 1.0;
+            this.backFaceCulling = true;
+            this.sideOrientation = Material.CounterClockWiseSideOrientation;
+            this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
+            this.disableDepthWrite = false;
+            this.fogEnabled = true;
+            this.pointSize = 1.0;
+            this.zOffset = 0;
+            this._wasPreviouslyReady = false;
+            this._fillMode = Material.TriangleFillMode;
+            this.id = name;
+            this._scene = scene;
+            if (!doNotAdd) {
+                scene.materials.push(this);
+            }
+        }
+        Object.defineProperty(Material, "TriangleFillMode", {
+            get: function () {
+                return Material._TriangleFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "WireFrameFillMode", {
+            get: function () {
+                return Material._WireFrameFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "PointFillMode", {
+            get: function () {
+                return Material._PointFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "ClockWiseSideOrientation", {
+            get: function () {
+                return Material._ClockWiseSideOrientation;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
+            get: function () {
+                return Material._CounterClockWiseSideOrientation;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "wireframe", {
+            get: function () {
+                return this._fillMode === Material.WireFrameFillMode;
+            },
+            set: function (value) {
+                this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "pointsCloud", {
+            get: function () {
+                return this._fillMode === Material.PointFillMode;
+            },
+            set: function (value) {
+                this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "fillMode", {
+            get: function () {
+                return this._fillMode;
+            },
+            set: function (value) {
+                this._fillMode = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "isFrozen", {
+            get: function () {
+                return this.checkReadyOnlyOnce;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Material.prototype.freeze = function () {
+            this.checkReadyOnlyOnce = true;
+        };
+        Material.prototype.unfreeze = function () {
+            this.checkReadyOnlyOnce = false;
+        };
+        Material.prototype.isReady = function (mesh, useInstances) {
+            return true;
+        };
+        Material.prototype.getEffect = function () {
+            return this._effect;
+        };
+        Material.prototype.getScene = function () {
+            return this._scene;
+        };
+        Material.prototype.needAlphaBlending = function () {
+            return (this.alpha < 1.0);
+        };
+        Material.prototype.needAlphaTesting = function () {
+            return false;
+        };
+        Material.prototype.getAlphaTestTexture = function () {
+            return null;
+        };
+        Material.prototype.trackCreation = function (onCompiled, onError) {
+        };
+        Material.prototype.markDirty = function () {
+            this._wasPreviouslyReady = false;
+        };
+        Material.prototype._preBind = function () {
+            var engine = this._scene.getEngine();
+            engine.enableEffect(this._effect);
+            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
+        };
+        Material.prototype.bind = function (world, mesh) {
+            this._scene._cachedMaterial = this;
+            if (this.onBind) {
+                this.onBind(this, mesh);
+            }
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                this._cachedDepthWriteState = engine.getDepthWrite();
+                engine.setDepthWrite(false);
+            }
+        };
+        Material.prototype.bindOnlyWorldMatrix = function (world) {
+        };
+        Material.prototype.unbind = function () {
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                engine.setDepthWrite(this._cachedDepthWriteState);
+            }
+        };
+        Material.prototype.clone = function (name) {
+            return null;
+        };
+        Material.prototype.getBindedMeshes = function () {
+            var result = new Array();
+            for (var index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.material === this) {
+                    result.push(mesh);
+                }
+            }
+            return result;
+        };
+        Material.prototype.dispose = function (forceDisposeEffect) {
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            var index = this._scene.materials.indexOf(this);
+            if (index >= 0) {
+                this._scene.materials.splice(index, 1);
+            }
+            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
+            if (forceDisposeEffect && this._effect) {
+                this._scene.getEngine()._releaseEffect(this._effect);
+                this._effect = null;
+            }
+            // Remove from meshes
+            for (index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.material === this) {
+                    mesh.material = null;
+                }
+            }
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        Material.prototype.serialize = function () {
+            return BABYLON.SerializationHelper.Serialize(this);
+        };
+        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
+            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
+            multiMaterial.id = parsedMultiMaterial.id;
+            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
+            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
+                var subMatId = parsedMultiMaterial.materials[matIndex];
+                if (subMatId) {
+                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
+                }
+                else {
+                    multiMaterial.subMaterials.push(null);
+                }
+            }
+            return multiMaterial;
+        };
+        Material.Parse = function (parsedMaterial, scene, rootUrl) {
+            if (!parsedMaterial.customType) {
+                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
+            }
+            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
+            return materialType.Parse(parsedMaterial, scene, rootUrl);
+            ;
+        };
+        Material._TriangleFillMode = 0;
+        Material._WireFrameFillMode = 1;
+        Material._PointFillMode = 2;
+        Material._ClockWiseSideOrientation = 0;
+        Material._CounterClockWiseSideOrientation = 1;
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "id", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "checkReadyOnEveryCall", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "checkReadyOnlyOnce", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "state", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "alpha", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "backFaceCulling", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "sideOrientation", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "alphaMode", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "disableDepthWrite", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "fogEnabled", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "pointSize", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "zOffset", void 0);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "wireframe", null);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "pointsCloud", null);
+        __decorate([
+            BABYLON.serialize()
+        ], Material.prototype, "fillMode", null);
+        return Material;
+    }());
+    BABYLON.Material = Material;
+})(BABYLON || (BABYLON = {}));

+ 204 - 204
src/Materials/babylon.materialHelper.js

@@ -1,204 +1,204 @@
-var BABYLON;
-(function (BABYLON) {
-    var maxSimultaneousLights = 4;
-    var MaterialHelper = (function () {
-        function MaterialHelper() {
-        }
-        MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
-            var lightIndex = 0;
-            var needNormals = false;
-            for (var index = 0; index < scene.lights.length; index++) {
-                var light = scene.lights[index];
-                if (!light.isEnabled()) {
-                    continue;
-                }
-                // Excluded check
-                if (light._excludedMeshesIds.length > 0) {
-                    for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
-                        var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
-                        if (excludedMesh) {
-                            light.excludedMeshes.push(excludedMesh);
-                        }
-                    }
-                    light._excludedMeshesIds = [];
-                }
-                // Included check
-                if (light._includedOnlyMeshesIds.length > 0) {
-                    for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
-                        var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
-                        if (includedOnlyMesh) {
-                            light.includedOnlyMeshes.push(includedOnlyMesh);
-                        }
-                    }
-                    light._includedOnlyMeshesIds = [];
-                }
-                if (!light.canAffectMesh(mesh)) {
-                    continue;
-                }
-                needNormals = true;
-                defines["LIGHT" + lightIndex] = true;
-                var type;
-                if (light instanceof BABYLON.SpotLight) {
-                    type = "SPOTLIGHT" + lightIndex;
-                }
-                else if (light instanceof BABYLON.HemisphericLight) {
-                    type = "HEMILIGHT" + lightIndex;
-                }
-                else if (light instanceof BABYLON.PointLight) {
-                    type = "POINTLIGHT" + lightIndex;
-                }
-                else {
-                    type = "DIRLIGHT" + lightIndex;
-                }
-                defines[type] = true;
-                // Specular
-                if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
-                    defines["SPECULARTERM"] = true;
-                }
-                // Shadows
-                if (scene.shadowsEnabled) {
-                    var shadowGenerator = light.getShadowGenerator();
-                    if (mesh && mesh.receiveShadows && shadowGenerator) {
-                        defines["SHADOW" + lightIndex] = true;
-                        defines["SHADOWS"] = true;
-                        if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
-                            defines["SHADOWVSM" + lightIndex] = true;
-                        }
-                        if (shadowGenerator.usePoissonSampling) {
-                            defines["SHADOWPCF" + lightIndex] = true;
-                        }
-                    }
-                }
-                lightIndex++;
-                if (lightIndex === maxSimultaneousLights)
-                    break;
-            }
-            return needNormals;
-        };
-        MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
-            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
-                if (!defines["LIGHT" + lightIndex]) {
-                    continue;
-                }
-                if (lightIndex > 0) {
-                    fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
-                }
-                if (defines["SHADOW" + lightIndex]) {
-                    fallbacks.addFallback(0, "SHADOW" + lightIndex);
-                }
-                if (defines["SHADOWPCF" + lightIndex]) {
-                    fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
-                }
-                if (defines["SHADOWVSM" + lightIndex]) {
-                    fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
-                }
-            }
-        };
-        MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
-            if (defines["NUM_BONE_INFLUENCERS"] > 0) {
-                fallbacks.addCPUSkinningFallback(0, mesh);
-                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
-                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
-                if (defines["NUM_BONE_INFLUENCERS"] > 4) {
-                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
-                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
-                }
-            }
-        };
-        MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
-            if (defines["INSTANCES"]) {
-                attribs.push("world0");
-                attribs.push("world1");
-                attribs.push("world2");
-                attribs.push("world3");
-            }
-        };
-        // Bindings
-        MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
-            var shadowGenerator = light.getShadowGenerator();
-            if (mesh.receiveShadows && shadowGenerator) {
-                if (!light.needCube()) {
-                    effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
-                }
-                else {
-                    if (!depthValuesAlreadySet) {
-                        depthValuesAlreadySet = true;
-                        effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
-                    }
-                }
-                effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
-                effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
-            }
-            return depthValuesAlreadySet;
-        };
-        MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
-            if (light instanceof BABYLON.PointLight) {
-                // Point Light
-                light.transferToEffect(effect, "vLightData" + lightIndex);
-            }
-            else if (light instanceof BABYLON.DirectionalLight) {
-                // Directional Light
-                light.transferToEffect(effect, "vLightData" + lightIndex);
-            }
-            else if (light instanceof BABYLON.SpotLight) {
-                // Spot Light
-                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
-            }
-            else if (light instanceof BABYLON.HemisphericLight) {
-                // Hemispheric Light
-                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
-            }
-        };
-        MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
-            var lightIndex = 0;
-            var depthValuesAlreadySet = false;
-            for (var index = 0; index < scene.lights.length; index++) {
-                var light = scene.lights[index];
-                if (!light.isEnabled()) {
-                    continue;
-                }
-                if (!light.canAffectMesh(mesh)) {
-                    continue;
-                }
-                MaterialHelper.BindLightProperties(light, effect, lightIndex);
-                light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
-                effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
-                if (defines["SPECULARTERM"]) {
-                    light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
-                    effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
-                }
-                // Shadows
-                if (scene.shadowsEnabled) {
-                    depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
-                }
-                lightIndex++;
-                if (lightIndex === maxSimultaneousLights)
-                    break;
-            }
-        };
-        MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
-            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-                effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
-                effect.setColor3("vFogColor", scene.fogColor);
-            }
-        };
-        MaterialHelper.BindBonesParameters = function (mesh, effect) {
-            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-            }
-        };
-        MaterialHelper.BindLogDepth = function (defines, effect, scene) {
-            if (defines["LOGARITHMICDEPTH"]) {
-                effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
-            }
-        };
-        MaterialHelper.BindClipPlane = function (effect, scene) {
-            if (scene.clipPlane) {
-                var clipPlane = scene.clipPlane;
-                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
-            }
-        };
-        return MaterialHelper;
-    })();
-    BABYLON.MaterialHelper = MaterialHelper;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var maxSimultaneousLights = 4;
+    var MaterialHelper = (function () {
+        function MaterialHelper() {
+        }
+        MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
+            var lightIndex = 0;
+            var needNormals = false;
+            for (var index = 0; index < scene.lights.length; index++) {
+                var light = scene.lights[index];
+                if (!light.isEnabled()) {
+                    continue;
+                }
+                // Excluded check
+                if (light._excludedMeshesIds.length > 0) {
+                    for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
+                        var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
+                        if (excludedMesh) {
+                            light.excludedMeshes.push(excludedMesh);
+                        }
+                    }
+                    light._excludedMeshesIds = [];
+                }
+                // Included check
+                if (light._includedOnlyMeshesIds.length > 0) {
+                    for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
+                        var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
+                        if (includedOnlyMesh) {
+                            light.includedOnlyMeshes.push(includedOnlyMesh);
+                        }
+                    }
+                    light._includedOnlyMeshesIds = [];
+                }
+                if (!light.canAffectMesh(mesh)) {
+                    continue;
+                }
+                needNormals = true;
+                defines["LIGHT" + lightIndex] = true;
+                var type;
+                if (light instanceof BABYLON.SpotLight) {
+                    type = "SPOTLIGHT" + lightIndex;
+                }
+                else if (light instanceof BABYLON.HemisphericLight) {
+                    type = "HEMILIGHT" + lightIndex;
+                }
+                else if (light instanceof BABYLON.PointLight) {
+                    type = "POINTLIGHT" + lightIndex;
+                }
+                else {
+                    type = "DIRLIGHT" + lightIndex;
+                }
+                defines[type] = true;
+                // Specular
+                if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
+                    defines["SPECULARTERM"] = true;
+                }
+                // Shadows
+                if (scene.shadowsEnabled) {
+                    var shadowGenerator = light.getShadowGenerator();
+                    if (mesh && mesh.receiveShadows && shadowGenerator) {
+                        defines["SHADOW" + lightIndex] = true;
+                        defines["SHADOWS"] = true;
+                        if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
+                            defines["SHADOWVSM" + lightIndex] = true;
+                        }
+                        if (shadowGenerator.usePoissonSampling) {
+                            defines["SHADOWPCF" + lightIndex] = true;
+                        }
+                    }
+                }
+                lightIndex++;
+                if (lightIndex === maxSimultaneousLights)
+                    break;
+            }
+            return needNormals;
+        };
+        MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
+            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
+                if (!defines["LIGHT" + lightIndex]) {
+                    continue;
+                }
+                if (lightIndex > 0) {
+                    fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
+                }
+                if (defines["SHADOW" + lightIndex]) {
+                    fallbacks.addFallback(0, "SHADOW" + lightIndex);
+                }
+                if (defines["SHADOWPCF" + lightIndex]) {
+                    fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
+                }
+                if (defines["SHADOWVSM" + lightIndex]) {
+                    fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
+                }
+            }
+        };
+        MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
+            if (defines["NUM_BONE_INFLUENCERS"] > 0) {
+                fallbacks.addCPUSkinningFallback(0, mesh);
+                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                if (defines["NUM_BONE_INFLUENCERS"] > 4) {
+                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
+                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
+                }
+            }
+        };
+        MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
+            if (defines["INSTANCES"]) {
+                attribs.push("world0");
+                attribs.push("world1");
+                attribs.push("world2");
+                attribs.push("world3");
+            }
+        };
+        // Bindings
+        MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
+            var shadowGenerator = light.getShadowGenerator();
+            if (mesh.receiveShadows && shadowGenerator) {
+                if (!light.needCube()) {
+                    effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
+                }
+                else {
+                    if (!depthValuesAlreadySet) {
+                        depthValuesAlreadySet = true;
+                        effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
+                    }
+                }
+                effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
+                effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
+            }
+            return depthValuesAlreadySet;
+        };
+        MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
+            if (light instanceof BABYLON.PointLight) {
+                // Point Light
+                light.transferToEffect(effect, "vLightData" + lightIndex);
+            }
+            else if (light instanceof BABYLON.DirectionalLight) {
+                // Directional Light
+                light.transferToEffect(effect, "vLightData" + lightIndex);
+            }
+            else if (light instanceof BABYLON.SpotLight) {
+                // Spot Light
+                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
+            }
+            else if (light instanceof BABYLON.HemisphericLight) {
+                // Hemispheric Light
+                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
+            }
+        };
+        MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
+            var lightIndex = 0;
+            var depthValuesAlreadySet = false;
+            for (var index = 0; index < scene.lights.length; index++) {
+                var light = scene.lights[index];
+                if (!light.isEnabled()) {
+                    continue;
+                }
+                if (!light.canAffectMesh(mesh)) {
+                    continue;
+                }
+                MaterialHelper.BindLightProperties(light, effect, lightIndex);
+                light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
+                effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
+                if (defines["SPECULARTERM"]) {
+                    light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
+                    effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
+                }
+                // Shadows
+                if (scene.shadowsEnabled) {
+                    depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
+                }
+                lightIndex++;
+                if (lightIndex === maxSimultaneousLights)
+                    break;
+            }
+        };
+        MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
+            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
+                effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
+                effect.setColor3("vFogColor", scene.fogColor);
+            }
+        };
+        MaterialHelper.BindBonesParameters = function (mesh, effect) {
+            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
+                effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
+            }
+        };
+        MaterialHelper.BindLogDepth = function (defines, effect, scene) {
+            if (defines["LOGARITHMICDEPTH"]) {
+                effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
+            }
+        };
+        MaterialHelper.BindClipPlane = function (effect, scene) {
+            if (scene.clipPlane) {
+                var clipPlane = scene.clipPlane;
+                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
+        };
+        return MaterialHelper;
+    }());
+    BABYLON.MaterialHelper = MaterialHelper;
+})(BABYLON || (BABYLON = {}));

+ 68 - 68
src/Materials/babylon.multiMaterial.js

@@ -1,68 +1,68 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var MultiMaterial = (function (_super) {
-        __extends(MultiMaterial, _super);
-        function MultiMaterial(name, scene) {
-            _super.call(this, name, scene, true);
-            this.subMaterials = new Array();
-            scene.multiMaterials.push(this);
-        }
-        // Properties
-        MultiMaterial.prototype.getSubMaterial = function (index) {
-            if (index < 0 || index >= this.subMaterials.length) {
-                return this.getScene().defaultMaterial;
-            }
-            return this.subMaterials[index];
-        };
-        // Methods
-        MultiMaterial.prototype.isReady = function (mesh) {
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = this.subMaterials[index];
-                if (subMaterial) {
-                    if (!this.subMaterials[index].isReady(mesh)) {
-                        return false;
-                    }
-                }
-            }
-            return true;
-        };
-        MultiMaterial.prototype.clone = function (name, cloneChildren) {
-            var newMultiMaterial = new MultiMaterial(name, this.getScene());
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = null;
-                if (cloneChildren) {
-                    subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
-                }
-                else {
-                    subMaterial = this.subMaterials[index];
-                }
-                newMultiMaterial.subMaterials.push(subMaterial);
-            }
-            return newMultiMaterial;
-        };
-        MultiMaterial.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.tags = BABYLON.Tags.GetTags(this);
-            serializationObject.materials = [];
-            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
-                var subMat = this.subMaterials[matIndex];
-                if (subMat) {
-                    serializationObject.materials.push(subMat.id);
-                }
-                else {
-                    serializationObject.materials.push(null);
-                }
-            }
-            return serializationObject;
-        };
-        return MultiMaterial;
-    })(BABYLON.Material);
-    BABYLON.MultiMaterial = MultiMaterial;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var MultiMaterial = (function (_super) {
+        __extends(MultiMaterial, _super);
+        function MultiMaterial(name, scene) {
+            _super.call(this, name, scene, true);
+            this.subMaterials = new Array();
+            scene.multiMaterials.push(this);
+        }
+        // Properties
+        MultiMaterial.prototype.getSubMaterial = function (index) {
+            if (index < 0 || index >= this.subMaterials.length) {
+                return this.getScene().defaultMaterial;
+            }
+            return this.subMaterials[index];
+        };
+        // Methods
+        MultiMaterial.prototype.isReady = function (mesh) {
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = this.subMaterials[index];
+                if (subMaterial) {
+                    if (!this.subMaterials[index].isReady(mesh)) {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        };
+        MultiMaterial.prototype.clone = function (name, cloneChildren) {
+            var newMultiMaterial = new MultiMaterial(name, this.getScene());
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = null;
+                if (cloneChildren) {
+                    subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
+                }
+                else {
+                    subMaterial = this.subMaterials[index];
+                }
+                newMultiMaterial.subMaterials.push(subMaterial);
+            }
+            return newMultiMaterial;
+        };
+        MultiMaterial.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.tags = BABYLON.Tags.GetTags(this);
+            serializationObject.materials = [];
+            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
+                var subMat = this.subMaterials[matIndex];
+                if (subMat) {
+                    serializationObject.materials.push(subMat.id);
+                }
+                else {
+                    serializationObject.materials.push(null);
+                }
+            }
+            return serializationObject;
+        };
+        return MultiMaterial;
+    }(BABYLON.Material));
+    BABYLON.MultiMaterial = MultiMaterial;
+})(BABYLON || (BABYLON = {}));

+ 342 - 342
src/Materials/babylon.shaderMaterial.js

@@ -1,342 +1,342 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var ShaderMaterial = (function (_super) {
-        __extends(ShaderMaterial, _super);
-        function ShaderMaterial(name, scene, shaderPath, options) {
-            _super.call(this, name, scene);
-            this._textures = {};
-            this._floats = {};
-            this._floatsArrays = {};
-            this._colors3 = {};
-            this._colors4 = {};
-            this._vectors2 = {};
-            this._vectors3 = {};
-            this._vectors4 = {};
-            this._matrices = {};
-            this._matrices3x3 = {};
-            this._matrices2x2 = {};
-            this._cachedWorldViewMatrix = new BABYLON.Matrix();
-            this._shaderPath = shaderPath;
-            options.needAlphaBlending = options.needAlphaBlending || false;
-            options.needAlphaTesting = options.needAlphaTesting || false;
-            options.attributes = options.attributes || ["position", "normal", "uv"];
-            options.uniforms = options.uniforms || ["worldViewProjection"];
-            options.samplers = options.samplers || [];
-            options.defines = options.defines || [];
-            this._options = options;
-        }
-        ShaderMaterial.prototype.needAlphaBlending = function () {
-            return this._options.needAlphaBlending;
-        };
-        ShaderMaterial.prototype.needAlphaTesting = function () {
-            return this._options.needAlphaTesting;
-        };
-        ShaderMaterial.prototype._checkUniform = function (uniformName) {
-            if (this._options.uniforms.indexOf(uniformName) === -1) {
-                this._options.uniforms.push(uniformName);
-            }
-        };
-        ShaderMaterial.prototype.setTexture = function (name, texture) {
-            if (this._options.samplers.indexOf(name) === -1) {
-                this._options.samplers.push(name);
-            }
-            this._textures[name] = texture;
-            return this;
-        };
-        ShaderMaterial.prototype.setFloat = function (name, value) {
-            this._checkUniform(name);
-            this._floats[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setFloats = function (name, value) {
-            this._checkUniform(name);
-            this._floatsArrays[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setColor3 = function (name, value) {
-            this._checkUniform(name);
-            this._colors3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setColor4 = function (name, value) {
-            this._checkUniform(name);
-            this._colors4[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector2 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors2[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector3 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector4 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors4[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix = function (name, value) {
-            this._checkUniform(name);
-            this._matrices[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
-            this._checkUniform(name);
-            this._matrices3x3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
-            this._checkUniform(name);
-            this._matrices2x2[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            if (!this.checkReadyOnEveryCall) {
-                if (this._renderId === scene.getRenderId()) {
-                    return true;
-                }
-            }
-            // Instances
-            var defines = [];
-            var fallbacks = new BABYLON.EffectFallbacks();
-            if (useInstances) {
-                defines.push("#define INSTANCES");
-            }
-            for (var index = 0; index < this._options.defines.length; index++) {
-                defines.push(this._options.defines[index]);
-            }
-            // Bones
-            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
-                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
-                fallbacks.addCPUSkinningFallback(0, mesh);
-            }
-            // Alpha test
-            if (engine.getAlphaTesting()) {
-                defines.push("#define ALPHATEST");
-            }
-            var previousEffect = this._effect;
-            var join = defines.join("\n");
-            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
-            if (!this._effect.isReady()) {
-                return false;
-            }
-            if (previousEffect !== this._effect) {
-                scene.resetCachedMaterial();
-            }
-            this._renderId = scene.getRenderId();
-            return true;
-        };
-        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
-            var scene = this.getScene();
-            if (this._options.uniforms.indexOf("world") !== -1) {
-                this._effect.setMatrix("world", world);
-            }
-            if (this._options.uniforms.indexOf("worldView") !== -1) {
-                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
-                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
-            }
-            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
-                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
-            }
-        };
-        ShaderMaterial.prototype.bind = function (world, mesh) {
-            // Std values
-            this.bindOnlyWorldMatrix(world);
-            if (this.getScene().getCachedMaterial() !== this) {
-                if (this._options.uniforms.indexOf("view") !== -1) {
-                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
-                }
-                if (this._options.uniforms.indexOf("projection") !== -1) {
-                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
-                }
-                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
-                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
-                }
-                // Bones
-                if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                    this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-                }
-                // Texture
-                for (var name in this._textures) {
-                    this._effect.setTexture(name, this._textures[name]);
-                }
-                // Float    
-                for (name in this._floats) {
-                    this._effect.setFloat(name, this._floats[name]);
-                }
-                // Float s   
-                for (name in this._floatsArrays) {
-                    this._effect.setArray(name, this._floatsArrays[name]);
-                }
-                // Color3        
-                for (name in this._colors3) {
-                    this._effect.setColor3(name, this._colors3[name]);
-                }
-                // Color4      
-                for (name in this._colors4) {
-                    var color = this._colors4[name];
-                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
-                }
-                // Vector2        
-                for (name in this._vectors2) {
-                    this._effect.setVector2(name, this._vectors2[name]);
-                }
-                // Vector3        
-                for (name in this._vectors3) {
-                    this._effect.setVector3(name, this._vectors3[name]);
-                }
-                // Vector4        
-                for (name in this._vectors4) {
-                    this._effect.setVector4(name, this._vectors4[name]);
-                }
-                // Matrix      
-                for (name in this._matrices) {
-                    this._effect.setMatrix(name, this._matrices[name]);
-                }
-                // Matrix 3x3
-                for (name in this._matrices3x3) {
-                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
-                }
-                // Matrix 2x2
-                for (name in this._matrices2x2) {
-                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
-                }
-            }
-            _super.prototype.bind.call(this, world, mesh);
-        };
-        ShaderMaterial.prototype.clone = function (name) {
-            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
-            return newShaderMaterial;
-        };
-        ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
-            for (var name in this._textures) {
-                this._textures[name].dispose();
-            }
-            this._textures = {};
-            _super.prototype.dispose.call(this, forceDisposeEffect);
-        };
-        ShaderMaterial.prototype.serialize = function () {
-            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
-            serializationObject.customType = "BABYLON.ShaderMaterial";
-            serializationObject.options = this._options;
-            serializationObject.shaderPath = this._shaderPath;
-            // Texture
-            serializationObject.textures = {};
-            for (var name in this._textures) {
-                serializationObject.textures[name] = this._textures[name].serialize();
-            }
-            // Float    
-            serializationObject.floats = {};
-            for (name in this._floats) {
-                serializationObject.floats[name] = this._floats[name];
-            }
-            // Float s   
-            serializationObject.floatArrays = {};
-            for (name in this._floatsArrays) {
-                serializationObject.floatArrays[name] = this._floatsArrays[name];
-            }
-            // Color3    
-            serializationObject.colors3 = {};
-            for (name in this._colors3) {
-                serializationObject.colors3[name] = this._colors3[name].asArray();
-            }
-            // Color4  
-            serializationObject.colors4 = {};
-            for (name in this._colors4) {
-                serializationObject.colors4[name] = this._colors4[name].asArray();
-            }
-            // Vector2  
-            serializationObject.vectors2 = {};
-            for (name in this._vectors2) {
-                serializationObject.vectors2[name] = this._vectors2[name].asArray();
-            }
-            // Vector3        
-            serializationObject.vectors3 = {};
-            for (name in this._vectors3) {
-                serializationObject.vectors3[name] = this._vectors3[name].asArray();
-            }
-            // Vector4        
-            serializationObject.vectors4 = {};
-            for (name in this._vectors4) {
-                serializationObject.vectors4[name] = this._vectors4[name].asArray();
-            }
-            // Matrix      
-            serializationObject.matrices = {};
-            for (name in this._matrices) {
-                serializationObject.matrices[name] = this._matrices[name].asArray();
-            }
-            // Matrix 3x3
-            serializationObject.matrices3x3 = {};
-            for (name in this._matrices3x3) {
-                serializationObject.matrices3x3[name] = this._matrices3x3[name];
-            }
-            // Matrix 2x2
-            serializationObject.matrices2x2 = {};
-            for (name in this._matrices2x2) {
-                serializationObject.matrices2x2[name] = this._matrices2x2[name];
-            }
-            return serializationObject;
-        };
-        ShaderMaterial.Parse = function (source, scene, rootUrl) {
-            var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
-            // Texture
-            for (var name in source.textures) {
-                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
-            }
-            // Float    
-            for (name in source.floats) {
-                material.setFloat(name, source.floats[name]);
-            }
-            // Float s   
-            for (name in source.floatsArrays) {
-                material.setFloats(name, source.floatsArrays[name]);
-            }
-            // Color3        
-            for (name in source.colors3) {
-                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
-            }
-            // Color4      
-            for (name in source.colors4) {
-                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
-            }
-            // Vector2        
-            for (name in source.vectors2) {
-                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
-            }
-            // Vector3        
-            for (name in source.vectors3) {
-                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
-            }
-            // Vector4        
-            for (name in source.vectors4) {
-                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
-            }
-            // Matrix      
-            for (name in source.matrices) {
-                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
-            }
-            // Matrix 3x3
-            for (name in source.matrices3x3) {
-                material.setMatrix3x3(name, source.matrices3x3[name]);
-            }
-            // Matrix 2x2
-            for (name in source.matrices2x2) {
-                material.setMatrix2x2(name, source.matrices2x2[name]);
-            }
-            return material;
-        };
-        return ShaderMaterial;
-    })(BABYLON.Material);
-    BABYLON.ShaderMaterial = ShaderMaterial;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var ShaderMaterial = (function (_super) {
+        __extends(ShaderMaterial, _super);
+        function ShaderMaterial(name, scene, shaderPath, options) {
+            _super.call(this, name, scene);
+            this._textures = {};
+            this._floats = {};
+            this._floatsArrays = {};
+            this._colors3 = {};
+            this._colors4 = {};
+            this._vectors2 = {};
+            this._vectors3 = {};
+            this._vectors4 = {};
+            this._matrices = {};
+            this._matrices3x3 = {};
+            this._matrices2x2 = {};
+            this._cachedWorldViewMatrix = new BABYLON.Matrix();
+            this._shaderPath = shaderPath;
+            options.needAlphaBlending = options.needAlphaBlending || false;
+            options.needAlphaTesting = options.needAlphaTesting || false;
+            options.attributes = options.attributes || ["position", "normal", "uv"];
+            options.uniforms = options.uniforms || ["worldViewProjection"];
+            options.samplers = options.samplers || [];
+            options.defines = options.defines || [];
+            this._options = options;
+        }
+        ShaderMaterial.prototype.needAlphaBlending = function () {
+            return this._options.needAlphaBlending;
+        };
+        ShaderMaterial.prototype.needAlphaTesting = function () {
+            return this._options.needAlphaTesting;
+        };
+        ShaderMaterial.prototype._checkUniform = function (uniformName) {
+            if (this._options.uniforms.indexOf(uniformName) === -1) {
+                this._options.uniforms.push(uniformName);
+            }
+        };
+        ShaderMaterial.prototype.setTexture = function (name, texture) {
+            if (this._options.samplers.indexOf(name) === -1) {
+                this._options.samplers.push(name);
+            }
+            this._textures[name] = texture;
+            return this;
+        };
+        ShaderMaterial.prototype.setFloat = function (name, value) {
+            this._checkUniform(name);
+            this._floats[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setFloats = function (name, value) {
+            this._checkUniform(name);
+            this._floatsArrays[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setColor3 = function (name, value) {
+            this._checkUniform(name);
+            this._colors3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setColor4 = function (name, value) {
+            this._checkUniform(name);
+            this._colors4[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector2 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors2[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector3 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector4 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors4[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix = function (name, value) {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
+            this._checkUniform(name);
+            this._matrices3x3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
+            this._checkUniform(name);
+            this._matrices2x2[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            if (!this.checkReadyOnEveryCall) {
+                if (this._renderId === scene.getRenderId()) {
+                    return true;
+                }
+            }
+            // Instances
+            var defines = [];
+            var fallbacks = new BABYLON.EffectFallbacks();
+            if (useInstances) {
+                defines.push("#define INSTANCES");
+            }
+            for (var index = 0; index < this._options.defines.length; index++) {
+                defines.push(this._options.defines[index]);
+            }
+            // Bones
+            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
+                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
+                fallbacks.addCPUSkinningFallback(0, mesh);
+            }
+            // Alpha test
+            if (engine.getAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+            }
+            var previousEffect = this._effect;
+            var join = defines.join("\n");
+            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
+            if (!this._effect.isReady()) {
+                return false;
+            }
+            if (previousEffect !== this._effect) {
+                scene.resetCachedMaterial();
+            }
+            this._renderId = scene.getRenderId();
+            return true;
+        };
+        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
+            var scene = this.getScene();
+            if (this._options.uniforms.indexOf("world") !== -1) {
+                this._effect.setMatrix("world", world);
+            }
+            if (this._options.uniforms.indexOf("worldView") !== -1) {
+                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
+                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+            }
+            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
+                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
+            }
+        };
+        ShaderMaterial.prototype.bind = function (world, mesh) {
+            // Std values
+            this.bindOnlyWorldMatrix(world);
+            if (this.getScene().getCachedMaterial() !== this) {
+                if (this._options.uniforms.indexOf("view") !== -1) {
+                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
+                }
+                if (this._options.uniforms.indexOf("projection") !== -1) {
+                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+                }
+                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
+                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
+                }
+                // Bones
+                if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
+                    this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
+                }
+                // Texture
+                for (var name in this._textures) {
+                    this._effect.setTexture(name, this._textures[name]);
+                }
+                // Float    
+                for (name in this._floats) {
+                    this._effect.setFloat(name, this._floats[name]);
+                }
+                // Float s   
+                for (name in this._floatsArrays) {
+                    this._effect.setArray(name, this._floatsArrays[name]);
+                }
+                // Color3        
+                for (name in this._colors3) {
+                    this._effect.setColor3(name, this._colors3[name]);
+                }
+                // Color4      
+                for (name in this._colors4) {
+                    var color = this._colors4[name];
+                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
+                }
+                // Vector2        
+                for (name in this._vectors2) {
+                    this._effect.setVector2(name, this._vectors2[name]);
+                }
+                // Vector3        
+                for (name in this._vectors3) {
+                    this._effect.setVector3(name, this._vectors3[name]);
+                }
+                // Vector4        
+                for (name in this._vectors4) {
+                    this._effect.setVector4(name, this._vectors4[name]);
+                }
+                // Matrix      
+                for (name in this._matrices) {
+                    this._effect.setMatrix(name, this._matrices[name]);
+                }
+                // Matrix 3x3
+                for (name in this._matrices3x3) {
+                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
+                }
+                // Matrix 2x2
+                for (name in this._matrices2x2) {
+                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
+                }
+            }
+            _super.prototype.bind.call(this, world, mesh);
+        };
+        ShaderMaterial.prototype.clone = function (name) {
+            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
+            return newShaderMaterial;
+        };
+        ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
+            for (var name in this._textures) {
+                this._textures[name].dispose();
+            }
+            this._textures = {};
+            _super.prototype.dispose.call(this, forceDisposeEffect);
+        };
+        ShaderMaterial.prototype.serialize = function () {
+            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
+            serializationObject.customType = "BABYLON.ShaderMaterial";
+            serializationObject.options = this._options;
+            serializationObject.shaderPath = this._shaderPath;
+            // Texture
+            serializationObject.textures = {};
+            for (var name in this._textures) {
+                serializationObject.textures[name] = this._textures[name].serialize();
+            }
+            // Float    
+            serializationObject.floats = {};
+            for (name in this._floats) {
+                serializationObject.floats[name] = this._floats[name];
+            }
+            // Float s   
+            serializationObject.floatArrays = {};
+            for (name in this._floatsArrays) {
+                serializationObject.floatArrays[name] = this._floatsArrays[name];
+            }
+            // Color3    
+            serializationObject.colors3 = {};
+            for (name in this._colors3) {
+                serializationObject.colors3[name] = this._colors3[name].asArray();
+            }
+            // Color4  
+            serializationObject.colors4 = {};
+            for (name in this._colors4) {
+                serializationObject.colors4[name] = this._colors4[name].asArray();
+            }
+            // Vector2  
+            serializationObject.vectors2 = {};
+            for (name in this._vectors2) {
+                serializationObject.vectors2[name] = this._vectors2[name].asArray();
+            }
+            // Vector3        
+            serializationObject.vectors3 = {};
+            for (name in this._vectors3) {
+                serializationObject.vectors3[name] = this._vectors3[name].asArray();
+            }
+            // Vector4        
+            serializationObject.vectors4 = {};
+            for (name in this._vectors4) {
+                serializationObject.vectors4[name] = this._vectors4[name].asArray();
+            }
+            // Matrix      
+            serializationObject.matrices = {};
+            for (name in this._matrices) {
+                serializationObject.matrices[name] = this._matrices[name].asArray();
+            }
+            // Matrix 3x3
+            serializationObject.matrices3x3 = {};
+            for (name in this._matrices3x3) {
+                serializationObject.matrices3x3[name] = this._matrices3x3[name];
+            }
+            // Matrix 2x2
+            serializationObject.matrices2x2 = {};
+            for (name in this._matrices2x2) {
+                serializationObject.matrices2x2[name] = this._matrices2x2[name];
+            }
+            return serializationObject;
+        };
+        ShaderMaterial.Parse = function (source, scene, rootUrl) {
+            var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
+            // Texture
+            for (var name in source.textures) {
+                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
+            }
+            // Float    
+            for (name in source.floats) {
+                material.setFloat(name, source.floats[name]);
+            }
+            // Float s   
+            for (name in source.floatsArrays) {
+                material.setFloats(name, source.floatsArrays[name]);
+            }
+            // Color3        
+            for (name in source.colors3) {
+                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
+            }
+            // Color4      
+            for (name in source.colors4) {
+                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
+            }
+            // Vector2        
+            for (name in source.vectors2) {
+                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
+            }
+            // Vector3        
+            for (name in source.vectors3) {
+                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
+            }
+            // Vector4        
+            for (name in source.vectors4) {
+                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
+            }
+            // Matrix      
+            for (name in source.matrices) {
+                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
+            }
+            // Matrix 3x3
+            for (name in source.matrices3x3) {
+                material.setMatrix3x3(name, source.matrices3x3[name]);
+            }
+            // Matrix 2x2
+            for (name in source.matrices2x2) {
+                material.setMatrix2x2(name, source.matrices2x2[name]);
+            }
+            return material;
+        };
+        return ShaderMaterial;
+    }(BABYLON.Material));
+    BABYLON.ShaderMaterial = ShaderMaterial;
+})(BABYLON || (BABYLON = {}));

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 856 - 856
src/Materials/babylon.standardMaterial.js


+ 269 - 269
src/Math/babylon.math.SIMD.js

@@ -1,269 +1,269 @@
-var BABYLON;
-(function (BABYLON) {
-    var SIMDVector3 = (function () {
-        function SIMDVector3() {
-        }
-        SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
-            var v = SIMD.float32x4.loadXYZ(vector._data, 0);
-            var m0 = SIMD.float32x4.load(transformation.m, 0);
-            var m1 = SIMD.float32x4.load(transformation.m, 4);
-            var m2 = SIMD.float32x4.load(transformation.m, 8);
-            var m3 = SIMD.float32x4.load(transformation.m, 12);
-            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
-            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
-            SIMD.float32x4.storeXYZ(result._data, 0, r);
-        };
-        SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
-            var v0 = SIMD.float32x4.splat(x);
-            var v1 = SIMD.float32x4.splat(y);
-            var v2 = SIMD.float32x4.splat(z);
-            var m0 = SIMD.float32x4.load(transformation.m, 0);
-            var m1 = SIMD.float32x4.load(transformation.m, 4);
-            var m2 = SIMD.float32x4.load(transformation.m, 8);
-            var m3 = SIMD.float32x4.load(transformation.m, 12);
-            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
-            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
-            SIMD.float32x4.storeXYZ(result._data, 0, r);
-        };
-        return SIMDVector3;
-    })();
-    BABYLON.SIMDVector3 = SIMDVector3;
-    var SIMDMatrix = (function () {
-        function SIMDMatrix() {
-        }
-        SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
-            if (offset === void 0) { offset = 0; }
-            var tm = this.m;
-            var om = other.m;
-            var om0 = SIMD.float32x4.load(om, 0);
-            var om1 = SIMD.float32x4.load(om, 4);
-            var om2 = SIMD.float32x4.load(om, 8);
-            var om3 = SIMD.float32x4.load(om, 12);
-            var tm0 = SIMD.float32x4.load(tm, 0);
-            SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
-            var tm1 = SIMD.float32x4.load(tm, 4);
-            SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
-            var tm2 = SIMD.float32x4.load(tm, 8);
-            SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
-            var tm3 = SIMD.float32x4.load(tm, 12);
-            SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
-        };
-        SIMDMatrix.prototype.invertToRefSIMD = function (other) {
-            var src = this.m;
-            var dest = other.m;
-            var row0, row1, row2, row3;
-            var tmp1;
-            var minor0, minor1, minor2, minor3;
-            var det;
-            // Load the 4 rows
-            var src0 = SIMD.float32x4.load(src, 0);
-            var src1 = SIMD.float32x4.load(src, 4);
-            var src2 = SIMD.float32x4.load(src, 8);
-            var src3 = SIMD.float32x4.load(src, 12);
-            // Transpose the source matrix.  Sort of.  Not a true transpose operation
-            tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
-            row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
-            row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
-            row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
-            tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
-            row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
-            row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
-            row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
-            // This is a true transposition, but it will lead to an incorrect result
-            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
-            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
-            //row0  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
-            //row1  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
-            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
-            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
-            //row2  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
-            //row3  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
-            // ----
-            tmp1 = SIMD.float32x4.mul(row2, row3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor0 = SIMD.float32x4.mul(row1, tmp1);
-            minor1 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
-            minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
-            minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(row1, row2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
-            minor3 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
-            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
-            minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
-            minor2 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
-            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
-            minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
-            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
-            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
-            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
-            minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
-            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
-            minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
-            // Compute determinant
-            det = SIMD.float32x4.mul(row0, minor0);
-            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
-            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
-            tmp1 = SIMD.float32x4.reciprocalApproximation(det);
-            det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
-            det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
-            // These shuffles aren't necessary if the faulty transposition is done
-            // up at the top of this function.
-            //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
-            //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
-            //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
-            //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
-            // Compute final values by multiplying with 1/det
-            minor0 = SIMD.float32x4.mul(det, minor0);
-            minor1 = SIMD.float32x4.mul(det, minor1);
-            minor2 = SIMD.float32x4.mul(det, minor2);
-            minor3 = SIMD.float32x4.mul(det, minor3);
-            SIMD.float32x4.store(dest, 0, minor0);
-            SIMD.float32x4.store(dest, 4, minor1);
-            SIMD.float32x4.store(dest, 8, minor2);
-            SIMD.float32x4.store(dest, 12, minor3);
-            return this;
-        };
-        SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
-            var out = result.m;
-            var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
-            var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
-            var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
-            // cc.kmVec3Subtract(f, pCenter, pEye);
-            var f = SIMD.float32x4.sub(center, eye);
-            // cc.kmVec3Normalize(f, f);    
-            var tmp = SIMD.float32x4.mul(f, f);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Assign(up, pUp);
-            // cc.kmVec3Normalize(up, up);
-            tmp = SIMD.float32x4.mul(up, up);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Cross(s, f, up);
-            var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
-            // cc.kmVec3Normalize(s, s);
-            tmp = SIMD.float32x4.mul(s, s);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Cross(u, s, f);
-            var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
-            // cc.kmVec3Normalize(s, s);
-            tmp = SIMD.float32x4.mul(s, s);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            var zero = SIMD.float32x4.splat(0.0);
-            s = SIMD.float32x4.neg(s);
-            var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
-            var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
-            var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
-            var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
-            tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
-            tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
-            var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
-            var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
-            var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
-            var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
-            var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
-            var b3 = SIMD.float32x4.neg(eye);
-            b3 = SIMD.float32x4.withW(b3, 1.0);
-            SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
-        };
-        return SIMDMatrix;
-    })();
-    BABYLON.SIMDMatrix = SIMDMatrix;
-    var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
-    var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
-    var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
-    var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
-    var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
-    var SIMDHelper = (function () {
-        function SIMDHelper() {
-        }
-        Object.defineProperty(SIMDHelper, "IsEnabled", {
-            get: function () {
-                return SIMDHelper._isEnabled;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SIMDHelper.DisableSIMD = function () {
-            // Replace functions
-            BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
-            BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
-            BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
-            BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
-            SIMDHelper._isEnabled = false;
-        };
-        SIMDHelper.EnableSIMD = function () {
-            if (window.SIMD === undefined) {
-                return;
-            }
-            // Replace functions
-            BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
-            BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
-            BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
-            BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
-            Object.defineProperty(BABYLON.Vector3.prototype, "x", {
-                get: function () { return this._data[0]; },
-                set: function (value) {
-                    if (!this._data) {
-                        this._data = new Float32Array(3);
-                    }
-                    this._data[0] = value;
-                }
-            });
-            Object.defineProperty(BABYLON.Vector3.prototype, "y", {
-                get: function () { return this._data[1]; },
-                set: function (value) {
-                    this._data[1] = value;
-                }
-            });
-            Object.defineProperty(BABYLON.Vector3.prototype, "z", {
-                get: function () { return this._data[2]; },
-                set: function (value) {
-                    this._data[2] = value;
-                }
-            });
-            SIMDHelper._isEnabled = true;
-        };
-        SIMDHelper._isEnabled = false;
-        return SIMDHelper;
-    })();
-    BABYLON.SIMDHelper = SIMDHelper;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SIMDVector3 = (function () {
+        function SIMDVector3() {
+        }
+        SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
+            var v = SIMD.float32x4.loadXYZ(vector._data, 0);
+            var m0 = SIMD.float32x4.load(transformation.m, 0);
+            var m1 = SIMD.float32x4.load(transformation.m, 4);
+            var m2 = SIMD.float32x4.load(transformation.m, 8);
+            var m3 = SIMD.float32x4.load(transformation.m, 12);
+            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
+            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
+            SIMD.float32x4.storeXYZ(result._data, 0, r);
+        };
+        SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
+            var v0 = SIMD.float32x4.splat(x);
+            var v1 = SIMD.float32x4.splat(y);
+            var v2 = SIMD.float32x4.splat(z);
+            var m0 = SIMD.float32x4.load(transformation.m, 0);
+            var m1 = SIMD.float32x4.load(transformation.m, 4);
+            var m2 = SIMD.float32x4.load(transformation.m, 8);
+            var m3 = SIMD.float32x4.load(transformation.m, 12);
+            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
+            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
+            SIMD.float32x4.storeXYZ(result._data, 0, r);
+        };
+        return SIMDVector3;
+    }());
+    BABYLON.SIMDVector3 = SIMDVector3;
+    var SIMDMatrix = (function () {
+        function SIMDMatrix() {
+        }
+        SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
+            if (offset === void 0) { offset = 0; }
+            var tm = this.m;
+            var om = other.m;
+            var om0 = SIMD.float32x4.load(om, 0);
+            var om1 = SIMD.float32x4.load(om, 4);
+            var om2 = SIMD.float32x4.load(om, 8);
+            var om3 = SIMD.float32x4.load(om, 12);
+            var tm0 = SIMD.float32x4.load(tm, 0);
+            SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
+            var tm1 = SIMD.float32x4.load(tm, 4);
+            SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
+            var tm2 = SIMD.float32x4.load(tm, 8);
+            SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
+            var tm3 = SIMD.float32x4.load(tm, 12);
+            SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
+        };
+        SIMDMatrix.prototype.invertToRefSIMD = function (other) {
+            var src = this.m;
+            var dest = other.m;
+            var row0, row1, row2, row3;
+            var tmp1;
+            var minor0, minor1, minor2, minor3;
+            var det;
+            // Load the 4 rows
+            var src0 = SIMD.float32x4.load(src, 0);
+            var src1 = SIMD.float32x4.load(src, 4);
+            var src2 = SIMD.float32x4.load(src, 8);
+            var src3 = SIMD.float32x4.load(src, 12);
+            // Transpose the source matrix.  Sort of.  Not a true transpose operation
+            tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+            row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+            row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
+            row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
+            tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+            row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+            row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
+            row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
+            // This is a true transposition, but it will lead to an incorrect result
+            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+            //row0  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
+            //row1  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
+            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+            //row2  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
+            //row3  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
+            // ----
+            tmp1 = SIMD.float32x4.mul(row2, row3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor0 = SIMD.float32x4.mul(row1, tmp1);
+            minor1 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
+            minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
+            minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(row1, row2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
+            minor3 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
+            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
+            minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
+            minor2 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
+            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
+            minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
+            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
+            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
+            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
+            minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
+            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
+            minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
+            // Compute determinant
+            det = SIMD.float32x4.mul(row0, minor0);
+            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
+            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
+            tmp1 = SIMD.float32x4.reciprocalApproximation(det);
+            det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
+            det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
+            // These shuffles aren't necessary if the faulty transposition is done
+            // up at the top of this function.
+            //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
+            //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
+            //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
+            //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
+            // Compute final values by multiplying with 1/det
+            minor0 = SIMD.float32x4.mul(det, minor0);
+            minor1 = SIMD.float32x4.mul(det, minor1);
+            minor2 = SIMD.float32x4.mul(det, minor2);
+            minor3 = SIMD.float32x4.mul(det, minor3);
+            SIMD.float32x4.store(dest, 0, minor0);
+            SIMD.float32x4.store(dest, 4, minor1);
+            SIMD.float32x4.store(dest, 8, minor2);
+            SIMD.float32x4.store(dest, 12, minor3);
+            return this;
+        };
+        SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
+            var out = result.m;
+            var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
+            var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
+            var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
+            // cc.kmVec3Subtract(f, pCenter, pEye);
+            var f = SIMD.float32x4.sub(center, eye);
+            // cc.kmVec3Normalize(f, f);    
+            var tmp = SIMD.float32x4.mul(f, f);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Assign(up, pUp);
+            // cc.kmVec3Normalize(up, up);
+            tmp = SIMD.float32x4.mul(up, up);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Cross(s, f, up);
+            var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
+            // cc.kmVec3Normalize(s, s);
+            tmp = SIMD.float32x4.mul(s, s);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Cross(u, s, f);
+            var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
+            // cc.kmVec3Normalize(s, s);
+            tmp = SIMD.float32x4.mul(s, s);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            var zero = SIMD.float32x4.splat(0.0);
+            s = SIMD.float32x4.neg(s);
+            var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
+            var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
+            var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+            var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
+            tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
+            tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
+            var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+            var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
+            var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
+            var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
+            var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
+            var b3 = SIMD.float32x4.neg(eye);
+            b3 = SIMD.float32x4.withW(b3, 1.0);
+            SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
+        };
+        return SIMDMatrix;
+    }());
+    BABYLON.SIMDMatrix = SIMDMatrix;
+    var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
+    var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
+    var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
+    var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
+    var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
+    var SIMDHelper = (function () {
+        function SIMDHelper() {
+        }
+        Object.defineProperty(SIMDHelper, "IsEnabled", {
+            get: function () {
+                return SIMDHelper._isEnabled;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SIMDHelper.DisableSIMD = function () {
+            // Replace functions
+            BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
+            BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
+            BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
+            BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
+            SIMDHelper._isEnabled = false;
+        };
+        SIMDHelper.EnableSIMD = function () {
+            if (window.SIMD === undefined) {
+                return;
+            }
+            // Replace functions
+            BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
+            BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
+            BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
+            BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
+            Object.defineProperty(BABYLON.Vector3.prototype, "x", {
+                get: function () { return this._data[0]; },
+                set: function (value) {
+                    if (!this._data) {
+                        this._data = new Float32Array(3);
+                    }
+                    this._data[0] = value;
+                }
+            });
+            Object.defineProperty(BABYLON.Vector3.prototype, "y", {
+                get: function () { return this._data[1]; },
+                set: function (value) {
+                    this._data[1] = value;
+                }
+            });
+            Object.defineProperty(BABYLON.Vector3.prototype, "z", {
+                get: function () { return this._data[2]; },
+                set: function (value) {
+                    this._data[2] = value;
+                }
+            });
+            SIMDHelper._isEnabled = true;
+        };
+        SIMDHelper._isEnabled = false;
+        return SIMDHelper;
+    }());
+    BABYLON.SIMDHelper = SIMDHelper;
+})(BABYLON || (BABYLON = {}));

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 2856 - 2856
src/Math/babylon.math.js


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 966 - 966
src/Mesh/babylon.abstractMesh.js


+ 0 - 0
src/Mesh/babylon.csg.js


Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä