Przeglądaj źródła

Nightly + added npm package.json

David Catuhe 9 lat temu
rodzic
commit
03fc003aa2
100 zmienionych plików z 25338 dodań i 25258 usunięć
  1. 40 0
      Tools/Npm/package.json
  2. 18 18
      dist/preview release/babylon.core.js
  3. 151 128
      dist/preview release/babylon.d.ts
  4. 34 34
      dist/preview release/babylon.js
  5. 67 2
      dist/preview release/babylon.max.js
  6. 38 38
      dist/preview release/babylon.noworker.js
  7. 131 132
      src/Actions/babylon.action.js
  8. 527 528
      src/Actions/babylon.actionManager.js
  9. 157 158
      src/Actions/babylon.condition.js
  10. 303 304
      src/Actions/babylon.directActions.js
  11. 77 78
      src/Actions/babylon.interpolateValueAction.js
  12. 132 133
      src/Animations/babylon.animatable.js
  13. 739 740
      src/Animations/babylon.animation.js
  14. 249 250
      src/Animations/babylon.easing.js
  15. 111 112
      src/Audio/babylon.analyser.js
  16. 115 116
      src/Audio/babylon.audioEngine.js
  17. 634 635
      src/Audio/babylon.sound.js
  18. 101 102
      src/Audio/babylon.soundtrack.js
  19. 141 142
      src/Bones/babylon.bone.js
  20. 339 340
      src/Bones/babylon.skeleton.js
  21. 71 72
      src/Cameras/Inputs/babylon.arcrotatecamera.input.gamepad.js
  22. 116 117
      src/Cameras/Inputs/babylon.arcrotatecamera.input.keyboard.js
  23. 57 58
      src/Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.js
  24. 212 213
      src/Cameras/Inputs/babylon.arcrotatecamera.input.pointers.js
  25. 48 49
      src/Cameras/Inputs/babylon.arcrotatecamera.input.vrdeviceorientation.js
  26. 65 66
      src/Cameras/Inputs/babylon.freecamera.input.deviceorientation.js
  27. 66 67
      src/Cameras/Inputs/babylon.freecamera.input.gamepad.js
  28. 118 119
      src/Cameras/Inputs/babylon.freecamera.input.keyboard.js
  29. 99 100
      src/Cameras/Inputs/babylon.freecamera.input.mouse.js
  30. 122 123
      src/Cameras/Inputs/babylon.freecamera.input.touch.js
  31. 54 55
      src/Cameras/Inputs/babylon.freecamera.input.virtualjoystick.js
  32. 72 73
      src/Cameras/VR/babylon.vrCameraMetrics.js
  33. 39 40
      src/Cameras/VR/babylon.vrDeviceOrientationCamera.js
  34. 106 107
      src/Cameras/VR/babylon.webVRCamera.js
  35. 548 549
      src/Cameras/babylon.arcRotateCamera.js
  36. 36 37
      src/Cameras/babylon.arcRotateCameraInputsManager.js
  37. 679 680
      src/Cameras/babylon.camera.js
  38. 133 134
      src/Cameras/babylon.cameraInputsManager.js
  39. 48 49
      src/Cameras/babylon.deviceOrientationCamera.js
  40. 117 118
      src/Cameras/babylon.followCamera.js
  41. 185 186
      src/Cameras/babylon.freeCamera.js
  42. 41 42
      src/Cameras/babylon.freeCameraInputsManager.js
  43. 51 52
      src/Cameras/babylon.gamepadCamera.js
  44. 116 117
      src/Cameras/babylon.stereoscopicCameras.js
  45. 269 270
      src/Cameras/babylon.targetCamera.js
  46. 58 59
      src/Cameras/babylon.touchCamera.js
  47. 51 52
      src/Cameras/babylon.universalCamera.js
  48. 18 19
      src/Cameras/babylon.virtualJoysticksCamera.js
  49. 211 212
      src/Canvas2d/babylon.bounding2d.js
  50. 212 213
      src/Canvas2d/babylon.brushes2d.js
  51. 1489 1490
      src/Canvas2d/babylon.canvas2d.js
  52. 174 175
      src/Canvas2d/babylon.canvas2dLayoutEngine.js
  53. 353 354
      src/Canvas2d/babylon.ellipse2d.js
  54. 927 928
      src/Canvas2d/babylon.group2d.js
  55. 1176 1177
      src/Canvas2d/babylon.lines2d.js
  56. 321 322
      src/Canvas2d/babylon.modelRenderCache.js
  57. 2978 2979
      src/Canvas2d/babylon.prim2dBase.js
  58. 451 452
      src/Canvas2d/babylon.rectangle2d.js
  59. 882 883
      src/Canvas2d/babylon.renderablePrim2d.js
  60. 290 291
      src/Canvas2d/babylon.shape2d.js
  61. 583 584
      src/Canvas2d/babylon.smartPropertyPrim.js
  62. 453 454
      src/Canvas2d/babylon.sprite2d.js
  63. 453 454
      src/Canvas2d/babylon.text2d.js
  64. 27 28
      src/Canvas2d/babylon.worldSpaceCanvas2dNode.js
  65. 276 277
      src/Collisions/babylon.collider.js
  66. 273 274
      src/Collisions/babylon.collisionCoordinator.js
  67. 243 244
      src/Collisions/babylon.collisionWorker.js
  68. 76 77
      src/Collisions/babylon.pickingInfo.js
  69. 88 89
      src/Culling/Octrees/babylon.octree.js
  70. 122 123
      src/Culling/Octrees/babylon.octreeBlock.js
  71. 143 144
      src/Culling/babylon.boundingBox.js
  72. 119 120
      src/Culling/babylon.boundingInfo.js
  73. 49 50
      src/Culling/babylon.boundingSphere.js
  74. 274 275
      src/Culling/babylon.ray.js
  75. 681 682
      src/Debug/babylon.debugLayer.js
  76. 137 138
      src/Debug/babylon.skeletonViewer.js
  77. 140 141
      src/Layer/babylon.layer.js
  78. 24 25
      src/LensFlare/babylon.lensFlare.js
  79. 214 215
      src/LensFlare/babylon.lensFlareSystem.js
  80. 425 426
      src/Lights/Shadows/babylon.shadowGenerator.js
  81. 129 130
      src/Lights/babylon.directionalLight.js
  82. 51 52
      src/Lights/babylon.hemisphericLight.js
  83. 239 195
      src/Lights/babylon.light.js
  84. 87 88
      src/Lights/babylon.pointLight.js
  85. 98 99
      src/Lights/babylon.spotLight.js
  86. 491 492
      src/Loading/Plugins/babylon.babylonFileLoader.js
  87. 263 264
      src/Loading/babylon.sceneLoader.js
  88. 124 125
      src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js
  89. 284 285
      src/Materials/Textures/Procedurals/babylon.proceduralTexture.js
  90. 187 188
      src/Materials/Textures/babylon.baseTexture.js
  91. 212 213
      src/Materials/Textures/babylon.colorGradingTexture.js
  92. 82 83
      src/Materials/Textures/babylon.cubeTexture.js
  93. 93 94
      src/Materials/Textures/babylon.dynamicTexture.js
  94. 313 314
      src/Materials/Textures/babylon.fontTexture.js
  95. 448 449
      src/Materials/Textures/babylon.hdrCubeTexture.js
  96. 111 112
      src/Materials/Textures/babylon.mapTexture.js
  97. 54 55
      src/Materials/Textures/babylon.mirrorTexture.js
  98. 57 58
      src/Materials/Textures/babylon.rawTexture.js
  99. 52 53
      src/Materials/Textures/babylon.refractionTexture.js
  100. 0 0
      src/Materials/Textures/babylon.renderTargetTexture.js

+ 40 - 0
Tools/Npm/package.json

@@ -0,0 +1,40 @@
+{
+  "author": {
+    "name": "David CATUHE"
+  },
+  "contributors": [
+    "David ROUSSET"
+  ],
+  "name": "babylonjs",
+  "description": "Babylon.js is a JavaScript 3D engine based on webgl.",
+  "version": "2.4.0",
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/BabylonJS/Babylon.js.git"
+  },
+  "main": "babylon.js",
+  "files": [
+    "babylon.d.ts",
+    "babylon.js",
+    "babylon.max.js",
+    "babylon.noworker.js",
+    "babylon.core.js",
+    "Oimo.js",
+    "package.json"
+  ],
+  "keywords": [
+    "3D",
+    "javascript",
+    "html5",
+    "webgl"
+  ],
+  "license": "Apache-2.0",
+  "dependencies": {},
+  "engines": {
+    "node": "*"
+  },
+  "readme": "Babylon.js is a 3D engine based on webgl and javascript",
+  "readmeFilename": "README.md",
+  "_id": "babylonjs@2.0.2",
+  "_from": "babylonjs@"
+}

Plik diff jest za duży
+ 18 - 18
dist/preview release/babylon.core.js


+ 151 - 128
dist/preview release/babylon.d.ts

@@ -5943,112 +5943,6 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
-    class BoundingBox implements ICullable {
-        minimum: Vector3;
-        maximum: Vector3;
-        vectors: Vector3[];
-        center: Vector3;
-        extendSize: Vector3;
-        directions: Vector3[];
-        vectorsWorld: Vector3[];
-        minimumWorld: Vector3;
-        maximumWorld: Vector3;
-        private _worldMatrix;
-        constructor(minimum: Vector3, maximum: Vector3);
-        getWorldMatrix(): Matrix;
-        setWorldMatrix(matrix: Matrix): BoundingBox;
-        _update(world: Matrix): void;
-        isInFrustum(frustumPlanes: Plane[]): boolean;
-        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
-        intersectsPoint(point: Vector3): boolean;
-        intersectsSphere(sphere: BoundingSphere): boolean;
-        intersectsMinMax(min: Vector3, max: Vector3): boolean;
-        static Intersects(box0: BoundingBox, box1: BoundingBox): boolean;
-        static IntersectsSphere(minPoint: Vector3, maxPoint: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean;
-        static IsCompletelyInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean;
-        static IsInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean;
-    }
-}
-
-declare module BABYLON {
-    interface ICullable {
-        isInFrustum(frustumPlanes: Plane[]): boolean;
-        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
-    }
-    class BoundingInfo implements ICullable {
-        minimum: Vector3;
-        maximum: Vector3;
-        boundingBox: BoundingBox;
-        boundingSphere: BoundingSphere;
-        private _isLocked;
-        constructor(minimum: Vector3, maximum: Vector3);
-        isLocked: boolean;
-        update(world: Matrix): void;
-        isInFrustum(frustumPlanes: Plane[]): boolean;
-        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
-        _checkCollision(collider: Collider): boolean;
-        intersectsPoint(point: Vector3): boolean;
-        intersects(boundingInfo: BoundingInfo, precise: boolean): boolean;
-    }
-}
-
-declare module BABYLON {
-    class BoundingSphere {
-        minimum: Vector3;
-        maximum: Vector3;
-        center: Vector3;
-        radius: number;
-        centerWorld: Vector3;
-        radiusWorld: number;
-        private _tempRadiusVector;
-        constructor(minimum: Vector3, maximum: Vector3);
-        _update(world: Matrix): void;
-        isInFrustum(frustumPlanes: Plane[]): boolean;
-        intersectsPoint(point: Vector3): boolean;
-        static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean;
-    }
-}
-
-declare module BABYLON {
-    class Ray {
-        origin: Vector3;
-        direction: Vector3;
-        length: number;
-        private _edge1;
-        private _edge2;
-        private _pvec;
-        private _tvec;
-        private _qvec;
-        constructor(origin: Vector3, direction: Vector3, length?: number);
-        intersectsBoxMinMax(minimum: Vector3, maximum: Vector3): boolean;
-        intersectsBox(box: BoundingBox): boolean;
-        intersectsSphere(sphere: BoundingSphere): boolean;
-        intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo;
-        intersectsPlane(plane: Plane): number;
-        private static smallnum;
-        private static rayl;
-        /**
-         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
-         * @param sega the first point of the segment to test the intersection against
-         * @param segb the second point of the segment to test the intersection against
-         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
-         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
-         */
-        intersectionSegment(sega: Vector3, segb: Vector3, threshold: number): number;
-        static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray;
-        /**
-        * 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.
-        */
-        static CreateNewFromTo(origin: Vector3, end: Vector3, world?: Matrix): Ray;
-        static Transform(ray: Ray, matrix: Matrix): Ray;
-    }
-}
-
-declare module BABYLON {
     class Collider {
         radius: Vector3;
         retry: number;
@@ -6290,6 +6184,112 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
+    class BoundingBox implements ICullable {
+        minimum: Vector3;
+        maximum: Vector3;
+        vectors: Vector3[];
+        center: Vector3;
+        extendSize: Vector3;
+        directions: Vector3[];
+        vectorsWorld: Vector3[];
+        minimumWorld: Vector3;
+        maximumWorld: Vector3;
+        private _worldMatrix;
+        constructor(minimum: Vector3, maximum: Vector3);
+        getWorldMatrix(): Matrix;
+        setWorldMatrix(matrix: Matrix): BoundingBox;
+        _update(world: Matrix): void;
+        isInFrustum(frustumPlanes: Plane[]): boolean;
+        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
+        intersectsPoint(point: Vector3): boolean;
+        intersectsSphere(sphere: BoundingSphere): boolean;
+        intersectsMinMax(min: Vector3, max: Vector3): boolean;
+        static Intersects(box0: BoundingBox, box1: BoundingBox): boolean;
+        static IntersectsSphere(minPoint: Vector3, maxPoint: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean;
+        static IsCompletelyInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean;
+        static IsInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean;
+    }
+}
+
+declare module BABYLON {
+    interface ICullable {
+        isInFrustum(frustumPlanes: Plane[]): boolean;
+        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
+    }
+    class BoundingInfo implements ICullable {
+        minimum: Vector3;
+        maximum: Vector3;
+        boundingBox: BoundingBox;
+        boundingSphere: BoundingSphere;
+        private _isLocked;
+        constructor(minimum: Vector3, maximum: Vector3);
+        isLocked: boolean;
+        update(world: Matrix): void;
+        isInFrustum(frustumPlanes: Plane[]): boolean;
+        isCompletelyInFrustum(frustumPlanes: Plane[]): boolean;
+        _checkCollision(collider: Collider): boolean;
+        intersectsPoint(point: Vector3): boolean;
+        intersects(boundingInfo: BoundingInfo, precise: boolean): boolean;
+    }
+}
+
+declare module BABYLON {
+    class BoundingSphere {
+        minimum: Vector3;
+        maximum: Vector3;
+        center: Vector3;
+        radius: number;
+        centerWorld: Vector3;
+        radiusWorld: number;
+        private _tempRadiusVector;
+        constructor(minimum: Vector3, maximum: Vector3);
+        _update(world: Matrix): void;
+        isInFrustum(frustumPlanes: Plane[]): boolean;
+        intersectsPoint(point: Vector3): boolean;
+        static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean;
+    }
+}
+
+declare module BABYLON {
+    class Ray {
+        origin: Vector3;
+        direction: Vector3;
+        length: number;
+        private _edge1;
+        private _edge2;
+        private _pvec;
+        private _tvec;
+        private _qvec;
+        constructor(origin: Vector3, direction: Vector3, length?: number);
+        intersectsBoxMinMax(minimum: Vector3, maximum: Vector3): boolean;
+        intersectsBox(box: BoundingBox): boolean;
+        intersectsSphere(sphere: BoundingSphere): boolean;
+        intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo;
+        intersectsPlane(plane: Plane): number;
+        private static smallnum;
+        private static rayl;
+        /**
+         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
+         * @param sega the first point of the segment to test the intersection against
+         * @param segb the second point of the segment to test the intersection against
+         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
+         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
+         */
+        intersectionSegment(sega: Vector3, segb: Vector3, threshold: number): number;
+        static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray;
+        /**
+        * 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.
+        */
+        static CreateNewFromTo(origin: Vector3, end: Vector3, world?: Matrix): Ray;
+        static Transform(ray: Ray, matrix: Matrix): Ray;
+    }
+}
+
+declare module BABYLON {
     class DebugLayer {
         private _scene;
         private _camera;
@@ -6518,6 +6518,28 @@ declare module BABYLON {
         _shadowGenerator: IShadowGenerator;
     }
     class Light extends Node {
+        private static _LIGHTMAP_DEFAULT;
+        private static _LIGHTMAP_SPECULAR;
+        private static _LIGHTMAP_SHADOWSONLY;
+        /**
+         * If every light affecting the material is in this lightmapMode,
+         * material.lightmapTexture adds or multiplies
+         * (depends on material.useLightmapAsShadowmap)
+         * after every other light calculations.
+         */
+        static LIGHTMAP_DEFAULT: number;
+        /**
+         * material.lightmapTexture as only diffuse lighting from this light
+         * adds pnly specular lighting from this light
+         * adds dynamic shadows
+         */
+        static LIGHTMAP_SPECULAR: number;
+        /**
+         * material.lightmapTexture as only lighting
+         * no light calculation from this light
+         * only adds dynamic shadows from this light
+         */
+        static LIGHTMAP_SHADOWSONLY: number;
         diffuse: Color3;
         specular: Color3;
         intensity: number;
@@ -6526,6 +6548,7 @@ declare module BABYLON {
         includedOnlyMeshes: AbstractMesh[];
         excludedMeshes: AbstractMesh[];
         excludeWithLayerMask: number;
+        lightmapMode: number;
         radius: number;
         _shadowGenerator: IShadowGenerator;
         private _parentedWorldMatrix;
@@ -11376,6 +11399,28 @@ declare module BABYLON {
 }
 
 declare module BABYLON {
+    class ReflectionProbe {
+        name: string;
+        private _scene;
+        private _renderTargetTexture;
+        private _projectionMatrix;
+        private _viewMatrix;
+        private _target;
+        private _add;
+        private _attachedMesh;
+        invertYAxis: boolean;
+        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 {
         private _passedProcess;
         constructor(name: string, options: number | PostProcessOptions, rigCameras: Camera[], samplingMode?: number, engine?: Engine, reusable?: boolean);
@@ -12032,28 +12077,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;
-        invertYAxis: boolean;
-        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;

Plik diff jest za duży
+ 34 - 34
dist/preview release/babylon.js


Plik diff jest za duży
+ 67 - 2
dist/preview release/babylon.max.js


Plik diff jest za duży
+ 38 - 38
dist/preview release/babylon.noworker.js


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

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

Plik diff jest za duży
+ 527 - 528
src/Actions/babylon.actionManager.js


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

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

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

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

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

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

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

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

Plik diff jest za duży
+ 739 - 740
src/Animations/babylon.animation.js


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

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

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

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

+ 115 - 116
src/Audio/babylon.audioEngine.js

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

Plik diff jest za duży
+ 634 - 635
src/Audio/babylon.sound.js


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

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

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

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

+ 339 - 340
src/Bones/babylon.skeleton.js

@@ -1,340 +1,339 @@
-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);
-            //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
-        /**
-         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
-         */
-        Skeleton.prototype.toString = function (fullDetails) {
-            var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
-            ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
-            if (fullDetails) {
-                ret += ", Ranges: {";
-                var first = true;
-                for (var name_1 in this._ranges) {
-                    if (first) {
-                        ret += ", ";
-                        first = false;
-                    }
-                    ret += name_1;
-                }
-                ret += "}";
-            }
-            return ret;
-        };
-        /**
-        * Get bone's index searching by name
-        * @param {string} name is bone's name to search for
-        * @return {number} Indice of the bone. Returns -1 if not found
-        */
-        Skeleton.prototype.getBoneIndexByName = function (name) {
-            for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
-                if (this.bones[boneIndex].name === name) {
-                    return boneIndex;
-                }
-            }
-            return -1;
-        };
-        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];
-        };
-        /**
-         *  Returns as an Array, all AnimationRanges defined on this skeleton
-         */
-        Skeleton.prototype.getAnimationRanges = function () {
-            var animationRanges = [];
-            var name;
-            var i = 0;
-            for (name in this._ranges) {
-                animationRanges[i] = this._ranges[name];
-                i++;
-            }
-            return animationRanges;
-        };
-        /**
-         *  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;
-            var nBones;
-            var i;
-            for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
-                boneDict[sourceBones[i].name] = sourceBones[i];
-            }
-            if (this.bones.length !== sourceBones.length) {
-                BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
-                ret = false;
-            }
-            var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
-            for (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, skelDimensionsRatio);
-                }
-                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;
-            }
-            return 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.addCount(this.bones.length, false);
-        };
-        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);
-            result.needInitialSkinMatrix = this.needInitialSkinMatrix;
-            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);
-            }
-            if (this._ranges) {
-                result._ranges = {};
-                for (var rangeName in this._ranges) {
-                    result._ranges[rangeName] = this._ranges[rangeName].clone();
-                }
-            }
-            this._isDirty = true;
-            return result;
-        };
-        Skeleton.prototype.enableBlending = function (blendingSpeed) {
-            if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
-            this.bones.forEach(function (bone) {
-                bone.animations.forEach(function (animation) {
-                    animation.enableBlending = true;
-                    animation.blendingSpeed = blendingSpeed;
-                });
-            });
-        };
-        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.dimensionsAtRest = this.dimensionsAtRest;
-            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);
-            if (parsedSkeleton.dimensionsAtRest) {
-                skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
-            }
-            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
-            var index;
-            for (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 (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 = {}));
-//# sourceMappingURL=babylon.skeleton.js.map
+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);
+            //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
+        /**
+         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
+         */
+        Skeleton.prototype.toString = function (fullDetails) {
+            var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
+            ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
+            if (fullDetails) {
+                ret += ", Ranges: {";
+                var first = true;
+                for (var name_1 in this._ranges) {
+                    if (first) {
+                        ret += ", ";
+                        first = false;
+                    }
+                    ret += name_1;
+                }
+                ret += "}";
+            }
+            return ret;
+        };
+        /**
+        * Get bone's index searching by name
+        * @param {string} name is bone's name to search for
+        * @return {number} Indice of the bone. Returns -1 if not found
+        */
+        Skeleton.prototype.getBoneIndexByName = function (name) {
+            for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
+                if (this.bones[boneIndex].name === name) {
+                    return boneIndex;
+                }
+            }
+            return -1;
+        };
+        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];
+        };
+        /**
+         *  Returns as an Array, all AnimationRanges defined on this skeleton
+         */
+        Skeleton.prototype.getAnimationRanges = function () {
+            var animationRanges = [];
+            var name;
+            var i = 0;
+            for (name in this._ranges) {
+                animationRanges[i] = this._ranges[name];
+                i++;
+            }
+            return animationRanges;
+        };
+        /**
+         *  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;
+            var nBones;
+            var i;
+            for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
+                boneDict[sourceBones[i].name] = sourceBones[i];
+            }
+            if (this.bones.length !== sourceBones.length) {
+                BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
+                ret = false;
+            }
+            var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
+            for (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, skelDimensionsRatio);
+                }
+                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;
+            }
+            return 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.addCount(this.bones.length, false);
+        };
+        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);
+            result.needInitialSkinMatrix = this.needInitialSkinMatrix;
+            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);
+            }
+            if (this._ranges) {
+                result._ranges = {};
+                for (var rangeName in this._ranges) {
+                    result._ranges[rangeName] = this._ranges[rangeName].clone();
+                }
+            }
+            this._isDirty = true;
+            return result;
+        };
+        Skeleton.prototype.enableBlending = function (blendingSpeed) {
+            if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
+            this.bones.forEach(function (bone) {
+                bone.animations.forEach(function (animation) {
+                    animation.enableBlending = true;
+                    animation.blendingSpeed = blendingSpeed;
+                });
+            });
+        };
+        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.dimensionsAtRest = this.dimensionsAtRest;
+            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);
+            if (parsedSkeleton.dimensionsAtRest) {
+                skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
+            }
+            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
+            var index;
+            for (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 (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 = {}));

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

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

+ 116 - 117
src/Cameras/Inputs/babylon.arcrotatecamera.input.keyboard.js

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

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

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

+ 212 - 213
src/Cameras/Inputs/babylon.arcrotatecamera.input.pointers.js

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

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

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

+ 65 - 66
src/Cameras/Inputs/babylon.freecamera.input.deviceorientation.js

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 39 - 40
src/Cameras/VR/babylon.vrDeviceOrientationCamera.js

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

+ 106 - 107
src/Cameras/VR/babylon.webVRCamera.js

@@ -1,107 +1,106 @@
-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, webVROptions) {
-            var _this = this;
-            if (compensateDistortion === void 0) { compensateDistortion = false; }
-            if (webVROptions === void 0) { webVROptions = {}; }
-            _super.call(this, name, position, scene);
-            this.webVROptions = webVROptions;
-            this._vrDevice = null;
-            this._cacheState = null;
-            this._vrEnabled = false;
-            //enable VR
-            this.getEngine().initWebVR();
-            if (!this.getEngine().vrDisplaysPromise) {
-                BABYLON.Tools.Error("WebVR is not enabled on your browser");
-            }
-            else {
-                //TODO get the metrics updated using the device's eye parameters!
-                //TODO also check that the device has the right capabilities!
-                this.getEngine().vrDisplaysPromise.then(function (devices) {
-                    if (devices.length > 0) {
-                        _this._vrEnabled = true;
-                        if (_this.webVROptions.displayName) {
-                            var found = devices.some(function (device) {
-                                if (device.displayName === _this.webVROptions.displayName) {
-                                    _this._vrDevice = device;
-                                    return true;
-                                }
-                                else {
-                                    return false;
-                                }
-                            });
-                            if (!found) {
-                                _this._vrDevice = devices[0];
-                                BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
-                            }
-                        }
-                        else {
-                            //choose the first one
-                            _this._vrDevice = devices[0];
-                        }
-                        //reset the rig parameters.
-                        _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
-                    }
-                    else {
-                        BABYLON.Tools.Error("No WebVR devices found!");
-                    }
-                });
-            }
-            this.rotationQuaternion = new BABYLON.Quaternion();
-            this._quaternionCache = new BABYLON.Quaternion();
-        }
-        WebVRFreeCamera.prototype._checkInputs = function () {
-            if (this._vrEnabled) {
-                var currentPost = this._vrDevice.getPose();
-                //make sure we have data
-                if (currentPost && currentPost.orientation) {
-                    this._cacheState = currentPost;
-                    this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
-                    if (this.webVROptions.trackPosition && this._cacheState.position) {
-                        this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
-                        this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
-                    }
-                    //Flip in XY plane
-                    this.rotationQuaternion.z *= -1;
-                    this.rotationQuaternion.w *= -1;
-                }
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
-            if (this._vrEnabled) {
-                this.getEngine().enableVR(this._vrDevice);
-            }
-        };
-        WebVRFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            this._vrEnabled = false;
-            this.getEngine().disableVR();
-        };
-        WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
-            //Backwards comp.
-            BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
-            //this.getEngine().switchFullscreen(requestPointerlock);
-        };
-        WebVRFreeCamera.prototype.getTypeName = function () {
-            return "WebVRFreeCamera";
-        };
-        WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
-            //uses the vrDisplay's "resetPose()".
-            //pitch and roll won't be affected.
-            this._vrDevice.resetPose();
-        };
-        return WebVRFreeCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.webVRCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var WebVRFreeCamera = (function (_super) {
+        __extends(WebVRFreeCamera, _super);
+        function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
+            var _this = this;
+            if (compensateDistortion === void 0) { compensateDistortion = false; }
+            if (webVROptions === void 0) { webVROptions = {}; }
+            _super.call(this, name, position, scene);
+            this.webVROptions = webVROptions;
+            this._vrDevice = null;
+            this._cacheState = null;
+            this._vrEnabled = false;
+            //enable VR
+            this.getEngine().initWebVR();
+            if (!this.getEngine().vrDisplaysPromise) {
+                BABYLON.Tools.Error("WebVR is not enabled on your browser");
+            }
+            else {
+                //TODO get the metrics updated using the device's eye parameters!
+                //TODO also check that the device has the right capabilities!
+                this.getEngine().vrDisplaysPromise.then(function (devices) {
+                    if (devices.length > 0) {
+                        _this._vrEnabled = true;
+                        if (_this.webVROptions.displayName) {
+                            var found = devices.some(function (device) {
+                                if (device.displayName === _this.webVROptions.displayName) {
+                                    _this._vrDevice = device;
+                                    return true;
+                                }
+                                else {
+                                    return false;
+                                }
+                            });
+                            if (!found) {
+                                _this._vrDevice = devices[0];
+                                BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
+                            }
+                        }
+                        else {
+                            //choose the first one
+                            _this._vrDevice = devices[0];
+                        }
+                        //reset the rig parameters.
+                        _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
+                    }
+                    else {
+                        BABYLON.Tools.Error("No WebVR devices found!");
+                    }
+                });
+            }
+            this.rotationQuaternion = new BABYLON.Quaternion();
+            this._quaternionCache = new BABYLON.Quaternion();
+        }
+        WebVRFreeCamera.prototype._checkInputs = function () {
+            if (this._vrEnabled) {
+                var currentPost = this._vrDevice.getPose();
+                //make sure we have data
+                if (currentPost && currentPost.orientation) {
+                    this._cacheState = currentPost;
+                    this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
+                    if (this.webVROptions.trackPosition && this._cacheState.position) {
+                        this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
+                        this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
+                    }
+                    //Flip in XY plane
+                    this.rotationQuaternion.z *= -1;
+                    this.rotationQuaternion.w *= -1;
+                }
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
+            if (this._vrEnabled) {
+                this.getEngine().enableVR(this._vrDevice);
+            }
+        };
+        WebVRFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            this._vrEnabled = false;
+            this.getEngine().disableVR();
+        };
+        WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
+            //Backwards comp.
+            BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
+            //this.getEngine().switchFullscreen(requestPointerlock);
+        };
+        WebVRFreeCamera.prototype.getTypeName = function () {
+            return "WebVRFreeCamera";
+        };
+        WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
+            //uses the vrDisplay's "resetPose()".
+            //pitch and roll won't be affected.
+            this._vrDevice.resetPose();
+        };
+        return WebVRFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
+})(BABYLON || (BABYLON = {}));

Plik diff jest za duży
+ 548 - 549
src/Cameras/babylon.arcRotateCamera.js


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

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

Plik diff jest za duży
+ 679 - 680
src/Cameras/babylon.camera.js


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

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

+ 48 - 49
src/Cameras/babylon.deviceOrientationCamera.js

@@ -1,49 +1,48 @@
-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);
-        function DeviceOrientationCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.inputs.addDeviceOrientation();
-        }
-        DeviceOrientationCamera.prototype.getTypeName = function () {
-            return "DeviceOrientationCamera";
-        };
-        DeviceOrientationCamera.prototype._checkInputs = function () {
-            _super.prototype._checkInputs.call(this);
-            if (this._initialQuaternion) {
-                this._quaternionCache.copyFrom(this.rotationQuaternion);
-                this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
-            }
-        };
-        DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
-            var _this = this;
-            if (axis === void 0) { axis = BABYLON.Axis.Y; }
-            //can only work if this camera has a rotation quaternion already.
-            if (!this.rotationQuaternion)
-                return;
-            if (!this._initialQuaternion) {
-                this._initialQuaternion = new BABYLON.Quaternion();
-            }
-            this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
-            ['x', 'y', 'z'].forEach(function (axisName) {
-                if (!axis[axisName]) {
-                    _this._initialQuaternion[axisName] = 0;
-                }
-                else {
-                    _this._initialQuaternion[axisName] *= -1;
-                }
-            });
-            this._initialQuaternion.normalize();
-        };
-        return DeviceOrientationCamera;
-    }(BABYLON.FreeCamera));
-    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.deviceOrientationCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var DeviceOrientationCamera = (function (_super) {
+        __extends(DeviceOrientationCamera, _super);
+        function DeviceOrientationCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.inputs.addDeviceOrientation();
+        }
+        DeviceOrientationCamera.prototype.getTypeName = function () {
+            return "DeviceOrientationCamera";
+        };
+        DeviceOrientationCamera.prototype._checkInputs = function () {
+            _super.prototype._checkInputs.call(this);
+            if (this._initialQuaternion) {
+                this._quaternionCache.copyFrom(this.rotationQuaternion);
+                this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
+            }
+        };
+        DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
+            var _this = this;
+            if (axis === void 0) { axis = BABYLON.Axis.Y; }
+            //can only work if this camera has a rotation quaternion already.
+            if (!this.rotationQuaternion)
+                return;
+            if (!this._initialQuaternion) {
+                this._initialQuaternion = new BABYLON.Quaternion();
+            }
+            this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
+            ['x', 'y', 'z'].forEach(function (axisName) {
+                if (!axis[axisName]) {
+                    _this._initialQuaternion[axisName] = 0;
+                }
+                else {
+                    _this._initialQuaternion[axisName] *= -1;
+                }
+            });
+            this._initialQuaternion.normalize();
+        };
+        return DeviceOrientationCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
+})(BABYLON || (BABYLON = {}));

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

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

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

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

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

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

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

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

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

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

+ 269 - 270
src/Cameras/babylon.targetCamera.js

@@ -1,270 +1,269 @@
-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._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
-            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);
-            this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, 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);
-            if (this.rotationQuaternion)
-                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
-        };
-        // 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.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
-        };
-        // Methods
-        TargetCamera.prototype._computeLocalCameraSpeed = function () {
-            var engine = this.getEngine();
-            return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
-        };
-        // Target
-        TargetCamera.prototype.setTarget = function (target) {
-            this.upVector.normalize();
-            BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, 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 = 0;
-            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;
-            }
-            if (this.rotationQuaternion) {
-                BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
-            }
-        };
-        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._updateCameraRotationMatrix = function () {
-            if (this.rotationQuaternion) {
-                this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
-                //update the up vector!
-                BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
-            }
-            else {
-                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-            }
-        };
-        TargetCamera.prototype._getViewMatrix = function () {
-            if (!this.lockedTarget) {
-                // Compute
-                this._updateCameraRotationMatrix();
-                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;
-        };
-        /**
-         * @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 || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
-                    if (!this.rotationQuaternion) {
-                        this.rotationQuaternion = new BABYLON.Quaternion();
-                    }
-                    rigCamera._cameraRigParams = {};
-                    rigCamera.rotationQuaternion = new BABYLON.Quaternion();
-                }
-                return rigCamera;
-            }
-            return null;
-        };
-        /**
-         * @override
-         * Override Camera._updateRigCameras
-         */
-        TargetCamera.prototype._updateRigCameras = function () {
-            var camLeft = this._rigCameras[0];
-            var camRight = this._rigCameras[1];
-            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:
-                    //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
-                    var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
-                    var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
-                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
-                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
-                    camLeft.setTarget(this.getTarget());
-                    camRight.setTarget(this.getTarget());
-                    break;
-                case BABYLON.Camera.RIG_MODE_VR:
-                case BABYLON.Camera.RIG_MODE_WEBVR:
-                    if (camLeft.rotationQuaternion) {
-                        camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
-                        camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
-                    }
-                    else {
-                        camLeft.rotation.copyFrom(this.rotation);
-                        camRight.rotation.copyFrom(this.rotation);
-                    }
-                    camLeft.position.copyFrom(this.position);
-                    camRight.position.copyFrom(this.position);
-                    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 = {}));
-//# sourceMappingURL=babylon.targetCamera.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var 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._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
+            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);
+            this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, 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);
+            if (this.rotationQuaternion)
+                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
+        };
+        // 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.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
+        };
+        // Methods
+        TargetCamera.prototype._computeLocalCameraSpeed = function () {
+            var engine = this.getEngine();
+            return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
+        };
+        // Target
+        TargetCamera.prototype.setTarget = function (target) {
+            this.upVector.normalize();
+            BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, 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 = 0;
+            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;
+            }
+            if (this.rotationQuaternion) {
+                BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
+            }
+        };
+        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._updateCameraRotationMatrix = function () {
+            if (this.rotationQuaternion) {
+                this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
+                //update the up vector!
+                BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
+            }
+            else {
+                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+            }
+        };
+        TargetCamera.prototype._getViewMatrix = function () {
+            if (!this.lockedTarget) {
+                // Compute
+                this._updateCameraRotationMatrix();
+                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;
+        };
+        /**
+         * @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 || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
+                    if (!this.rotationQuaternion) {
+                        this.rotationQuaternion = new BABYLON.Quaternion();
+                    }
+                    rigCamera._cameraRigParams = {};
+                    rigCamera.rotationQuaternion = new BABYLON.Quaternion();
+                }
+                return rigCamera;
+            }
+            return null;
+        };
+        /**
+         * @override
+         * Override Camera._updateRigCameras
+         */
+        TargetCamera.prototype._updateRigCameras = function () {
+            var camLeft = this._rigCameras[0];
+            var camRight = this._rigCameras[1];
+            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:
+                    //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
+                    var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
+                    var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
+                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
+                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
+                    camLeft.setTarget(this.getTarget());
+                    camRight.setTarget(this.getTarget());
+                    break;
+                case BABYLON.Camera.RIG_MODE_VR:
+                case BABYLON.Camera.RIG_MODE_WEBVR:
+                    if (camLeft.rotationQuaternion) {
+                        camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
+                        camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
+                    }
+                    else {
+                        camLeft.rotation.copyFrom(this.rotation);
+                        camRight.rotation.copyFrom(this.rotation);
+                    }
+                    camLeft.position.copyFrom(this.position);
+                    camRight.position.copyFrom(this.position);
+                    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 = {}));

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

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

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

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

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

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

+ 211 - 212
src/Canvas2d/babylon.bounding2d.js

@@ -1,212 +1,211 @@
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * Stores 2D Bounding Information.
-     * This class handles a circle area and a bounding rectangle one.
-     */
-    var BoundingInfo2D = (function () {
-        function BoundingInfo2D() {
-            this.radius = 0;
-            this.center = BABYLON.Vector2.Zero();
-            this.extent = BABYLON.Vector2.Zero();
-        }
-        /**
-         * Create a BoundingInfo2D object from a given size
-         * @param size the size that will be used to set the extend, radius will be computed from it.
-         */
-        BoundingInfo2D.CreateFromSize = function (size) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromSizeToRef(size, r);
-            return r;
-        };
-        /**
-         * Create a BoundingInfo2D object from a given radius
-         * @param radius the radius to use, the extent will be computed from it.
-         */
-        BoundingInfo2D.CreateFromRadius = function (radius) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromRadiusToRef(radius, r);
-            return r;
-        };
-        /**
-         * Create a BoundingInfo2D object from a list of points.
-         * The resulted object will be the smallest bounding area that includes all the given points.
-         * @param points an array of points to compute the bounding object from.
-         */
-        BoundingInfo2D.CreateFromPoints = function (points) {
-            var r = new BoundingInfo2D();
-            BoundingInfo2D.CreateFromPointsToRef(points, r);
-            return r;
-        };
-        /**
-         * Update a BoundingInfo2D object using the given Size as input
-         * @param size the bounding data will be computed from this size.
-         * @param b must be a valid/allocated object, it will contain the result of the operation
-         */
-        BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
-            if (!size) {
-                size = BABYLON.Size.Zero();
-            }
-            b.center.x = +size.width / 2;
-            b.center.y = +size.height / 2;
-            b.extent.x = b.center.x;
-            b.extent.y = b.center.y;
-            b.radius = b.extent.length();
-        };
-        /**
-         * Update a BoundingInfo2D object using the given radius as input
-         * @param radius the bounding data will be computed from this radius
-         * @param b must be a valid/allocated object, it will contain the result of the operation
-         */
-        BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
-            b.center.x = b.center.y = 0;
-            var r = +radius;
-            b.extent.x = r;
-            b.extent.y = r;
-            b.radius = r;
-        };
-        /**
-         * Update a BoundingInfo2D object using the given points array as input
-         * @param points the point array to use to update the bounding data
-         * @param b must be a valid/allocated object, it will contain the result of the operation
-         */
-        BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
-            var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
-            for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
-                var p = points_1[_i];
-                xmin = Math.min(p.x, xmin);
-                xmax = Math.max(p.x, xmax);
-                ymin = Math.min(p.y, ymin);
-                ymax = Math.max(p.y, ymax);
-            }
-            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
-        };
-        /**
-         * Update a BoundingInfo2D object using the given min/max values as input
-         * @param xmin the smallest x coordinate
-         * @param xmax the biggest x coordinate
-         * @param ymin the smallest y coordinate
-         * @param ymax the buggest y coordinate
-         * @param b must be a valid/allocated object, it will contain the result of the operation
-         */
-        BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
-            var w = xmax - xmin;
-            var h = ymax - ymin;
-            b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
-            b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
-            b.radius = b.extent.length();
-        };
-        /**
-         * Duplicate this instance and return a new one
-         * @return the duplicated instance
-         */
-        BoundingInfo2D.prototype.clone = function () {
-            var r = new BoundingInfo2D();
-            r.center = this.center.clone();
-            r.radius = this.radius;
-            r.extent = this.extent.clone();
-            return r;
-        };
-        BoundingInfo2D.prototype.clear = function () {
-            this.center.copyFromFloats(0, 0);
-            this.radius = 0;
-            this.extent.copyFromFloats(0, 0);
-        };
-        BoundingInfo2D.prototype.copyFrom = function (src) {
-            this.center.copyFrom(src.center);
-            this.radius = src.radius;
-            this.extent.copyFrom(src.extent);
-        };
-        /**
-         * return the max extend of the bounding info
-         */
-        BoundingInfo2D.prototype.max = function () {
-            var r = BABYLON.Vector2.Zero();
-            this.maxToRef(r);
-            return r;
-        };
-        /**
-         * Update a vector2 with the max extend of the bounding info
-         * @param result must be a valid/allocated vector2 that will contain the result of the operation
-         */
-        BoundingInfo2D.prototype.maxToRef = function (result) {
-            result.x = this.center.x + this.extent.x;
-            result.y = this.center.y + this.extent.y;
-        };
-        /**
-         * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
-         * @param matrix the transformation matrix to apply
-         * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
-         */
-        BoundingInfo2D.prototype.transform = function (matrix) {
-            var r = new BoundingInfo2D();
-            this.transformToRef(matrix, r);
-            return r;
-        };
-        /**
-         * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
-         * @param other the second BoundingInfo2D to compute the union with this one
-         * @return a new instance containing the result of the union
-         */
-        BoundingInfo2D.prototype.union = function (other) {
-            var r = new BoundingInfo2D();
-            this.unionToRef(other, r);
-            return r;
-        };
-        /**
-         * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
-         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
-         * @param matrix The matrix to use to compute the transformation
-         * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
-         */
-        BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
-            // Construct a bounding box based on the extent values
-            var p = BoundingInfo2D._transform;
-            p[0].x = this.center.x + this.extent.x;
-            p[0].y = this.center.y + this.extent.y;
-            p[1].x = this.center.x + this.extent.x;
-            p[1].y = this.center.y - this.extent.y;
-            p[2].x = this.center.x - this.extent.x;
-            p[2].y = this.center.y - this.extent.y;
-            p[3].x = this.center.x - this.extent.x;
-            p[3].y = this.center.y + this.extent.y;
-            // Transform the four points of the bounding box with the matrix
-            for (var i = 0; i < 4; i++) {
-                BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
-            }
-            BoundingInfo2D.CreateFromPointsToRef(p, result);
-        };
-        /**
-         * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
-         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
-         * @param other the second object used to compute the union
-         * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
-         */
-        BoundingInfo2D.prototype.unionToRef = function (other, result) {
-            var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
-            var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
-            var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
-            var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
-            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
-        };
-        /**
-         * Check if the given point is inside the BoundingInfo.
-         * The test is first made on the radius, then inside the rectangle described by the extent
-         * @param pickPosition the position to test
-         * @return true if the point is inside, false otherwise
-         */
-        BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
-            // is it inside the radius?
-            var pickLocal = pickPosition.subtract(this.center);
-            if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
-                // is it inside the rectangle?
-                return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
-            }
-            return false;
-        };
-        BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
-        return BoundingInfo2D;
-    }());
-    BABYLON.BoundingInfo2D = BoundingInfo2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.bounding2d.js.map
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Stores 2D Bounding Information.
+     * This class handles a circle area and a bounding rectangle one.
+     */
+    var BoundingInfo2D = (function () {
+        function BoundingInfo2D() {
+            this.radius = 0;
+            this.center = BABYLON.Vector2.Zero();
+            this.extent = BABYLON.Vector2.Zero();
+        }
+        /**
+         * Create a BoundingInfo2D object from a given size
+         * @param size the size that will be used to set the extend, radius will be computed from it.
+         */
+        BoundingInfo2D.CreateFromSize = function (size) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromSizeToRef(size, r);
+            return r;
+        };
+        /**
+         * Create a BoundingInfo2D object from a given radius
+         * @param radius the radius to use, the extent will be computed from it.
+         */
+        BoundingInfo2D.CreateFromRadius = function (radius) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromRadiusToRef(radius, r);
+            return r;
+        };
+        /**
+         * Create a BoundingInfo2D object from a list of points.
+         * The resulted object will be the smallest bounding area that includes all the given points.
+         * @param points an array of points to compute the bounding object from.
+         */
+        BoundingInfo2D.CreateFromPoints = function (points) {
+            var r = new BoundingInfo2D();
+            BoundingInfo2D.CreateFromPointsToRef(points, r);
+            return r;
+        };
+        /**
+         * Update a BoundingInfo2D object using the given Size as input
+         * @param size the bounding data will be computed from this size.
+         * @param b must be a valid/allocated object, it will contain the result of the operation
+         */
+        BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
+            if (!size) {
+                size = BABYLON.Size.Zero();
+            }
+            b.center.x = +size.width / 2;
+            b.center.y = +size.height / 2;
+            b.extent.x = b.center.x;
+            b.extent.y = b.center.y;
+            b.radius = b.extent.length();
+        };
+        /**
+         * Update a BoundingInfo2D object using the given radius as input
+         * @param radius the bounding data will be computed from this radius
+         * @param b must be a valid/allocated object, it will contain the result of the operation
+         */
+        BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
+            b.center.x = b.center.y = 0;
+            var r = +radius;
+            b.extent.x = r;
+            b.extent.y = r;
+            b.radius = r;
+        };
+        /**
+         * Update a BoundingInfo2D object using the given points array as input
+         * @param points the point array to use to update the bounding data
+         * @param b must be a valid/allocated object, it will contain the result of the operation
+         */
+        BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
+            var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
+            for (var _i = 0; _i < points.length; _i++) {
+                var p = points[_i];
+                xmin = Math.min(p.x, xmin);
+                xmax = Math.max(p.x, xmax);
+                ymin = Math.min(p.y, ymin);
+                ymax = Math.max(p.y, ymax);
+            }
+            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
+        };
+        /**
+         * Update a BoundingInfo2D object using the given min/max values as input
+         * @param xmin the smallest x coordinate
+         * @param xmax the biggest x coordinate
+         * @param ymin the smallest y coordinate
+         * @param ymax the buggest y coordinate
+         * @param b must be a valid/allocated object, it will contain the result of the operation
+         */
+        BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
+            var w = xmax - xmin;
+            var h = ymax - ymin;
+            b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
+            b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
+            b.radius = b.extent.length();
+        };
+        /**
+         * Duplicate this instance and return a new one
+         * @return the duplicated instance
+         */
+        BoundingInfo2D.prototype.clone = function () {
+            var r = new BoundingInfo2D();
+            r.center = this.center.clone();
+            r.radius = this.radius;
+            r.extent = this.extent.clone();
+            return r;
+        };
+        BoundingInfo2D.prototype.clear = function () {
+            this.center.copyFromFloats(0, 0);
+            this.radius = 0;
+            this.extent.copyFromFloats(0, 0);
+        };
+        BoundingInfo2D.prototype.copyFrom = function (src) {
+            this.center.copyFrom(src.center);
+            this.radius = src.radius;
+            this.extent.copyFrom(src.extent);
+        };
+        /**
+         * return the max extend of the bounding info
+         */
+        BoundingInfo2D.prototype.max = function () {
+            var r = BABYLON.Vector2.Zero();
+            this.maxToRef(r);
+            return r;
+        };
+        /**
+         * Update a vector2 with the max extend of the bounding info
+         * @param result must be a valid/allocated vector2 that will contain the result of the operation
+         */
+        BoundingInfo2D.prototype.maxToRef = function (result) {
+            result.x = this.center.x + this.extent.x;
+            result.y = this.center.y + this.extent.y;
+        };
+        /**
+         * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
+         * @param matrix the transformation matrix to apply
+         * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
+         */
+        BoundingInfo2D.prototype.transform = function (matrix) {
+            var r = new BoundingInfo2D();
+            this.transformToRef(matrix, r);
+            return r;
+        };
+        /**
+         * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
+         * @param other the second BoundingInfo2D to compute the union with this one
+         * @return a new instance containing the result of the union
+         */
+        BoundingInfo2D.prototype.union = function (other) {
+            var r = new BoundingInfo2D();
+            this.unionToRef(other, r);
+            return r;
+        };
+        /**
+         * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
+         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
+         * @param matrix The matrix to use to compute the transformation
+         * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
+         */
+        BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
+            // Construct a bounding box based on the extent values
+            var p = BoundingInfo2D._transform;
+            p[0].x = this.center.x + this.extent.x;
+            p[0].y = this.center.y + this.extent.y;
+            p[1].x = this.center.x + this.extent.x;
+            p[1].y = this.center.y - this.extent.y;
+            p[2].x = this.center.x - this.extent.x;
+            p[2].y = this.center.y - this.extent.y;
+            p[3].x = this.center.x - this.extent.x;
+            p[3].y = this.center.y + this.extent.y;
+            // Transform the four points of the bounding box with the matrix
+            for (var i = 0; i < 4; i++) {
+                BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
+            }
+            BoundingInfo2D.CreateFromPointsToRef(p, result);
+        };
+        /**
+         * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
+         * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
+         * @param other the second object used to compute the union
+         * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
+         */
+        BoundingInfo2D.prototype.unionToRef = function (other, result) {
+            var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
+            var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
+            var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
+            var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
+            BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
+        };
+        /**
+         * Check if the given point is inside the BoundingInfo.
+         * The test is first made on the radius, then inside the rectangle described by the extent
+         * @param pickPosition the position to test
+         * @return true if the point is inside, false otherwise
+         */
+        BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
+            // is it inside the radius?
+            var pickLocal = pickPosition.subtract(this.center);
+            if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
+                // is it inside the rectangle?
+                return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
+            }
+            return false;
+        };
+        BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
+        return BoundingInfo2D;
+    })();
+    BABYLON.BoundingInfo2D = BoundingInfo2D;
+})(BABYLON || (BABYLON = {}));

+ 212 - 213
src/Canvas2d/babylon.brushes2d.js

@@ -1,213 +1,212 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * Base class implementing the ILocable interface.
-     * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
-     */
-    var LockableBase = (function () {
-        function LockableBase() {
-        }
-        LockableBase.prototype.isLocked = function () {
-            return this._isLocked;
-        };
-        LockableBase.prototype.lock = function () {
-            if (this._isLocked) {
-                return true;
-            }
-            this.onLock();
-            this._isLocked = true;
-            return false;
-        };
-        /**
-         * Protected handler that will be called when the instance is about to be locked.
-         */
-        LockableBase.prototype.onLock = function () {
-        };
-        return LockableBase;
-    }());
-    BABYLON.LockableBase = LockableBase;
-    var SolidColorBrush2D = (function (_super) {
-        __extends(SolidColorBrush2D, _super);
-        function SolidColorBrush2D(color, lock) {
-            if (lock === void 0) { lock = false; }
-            _super.call(this);
-            this._color = color;
-            if (lock) {
-                {
-                    this.lock();
-                }
-            }
-        }
-        /**
-         * Return true if the brush is transparent, false if it's totally opaque
-         */
-        SolidColorBrush2D.prototype.isTransparent = function () {
-            return this._color && this._color.a < 1.0;
-        };
-        Object.defineProperty(SolidColorBrush2D.prototype, "color", {
-            /**
-             * The color used by this instance to render
-             * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
-             */
-            get: function () {
-                return this._color;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
-         */
-        SolidColorBrush2D.prototype.toString = function () {
-            return this._color.toHexString();
-        };
-        SolidColorBrush2D = __decorate([
-            BABYLON.className("SolidColorBrush2D")
-        ], SolidColorBrush2D);
-        return SolidColorBrush2D;
-    }(LockableBase));
-    BABYLON.SolidColorBrush2D = SolidColorBrush2D;
-    var GradientColorBrush2D = (function (_super) {
-        __extends(GradientColorBrush2D, _super);
-        function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
-            if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
-            if (rotation === void 0) { rotation = 0; }
-            if (scale === void 0) { scale = 1; }
-            if (lock === void 0) { lock = false; }
-            _super.call(this);
-            this._color1 = color1;
-            this._color2 = color2;
-            this._translation = translation;
-            this._rotation = rotation;
-            this._scale = scale;
-            if (lock) {
-                this.lock();
-            }
-        }
-        /**
-         * Return true if the brush is transparent, false if it's totally opaque
-         */
-        GradientColorBrush2D.prototype.isTransparent = function () {
-            return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
-        };
-        Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
-            /**
-             * First color, the blend will start from this color
-             */
-            get: function () {
-                return this._color1;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color1 = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
-            /**
-             * Second color, the blend will end to this color
-             */
-            get: function () {
-                return this._color2;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._color2 = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
-            /**
-             * Translation vector to apply on the blend
-             * Default is [0;0]
-             */
-            get: function () {
-                return this._translation;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._translation = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
-            /**
-             * Rotation in radian to apply to the brush
-             * Default direction of the brush is vertical, you can change this using this property.
-             * Default is 0.
-             */
-            get: function () {
-                return this._rotation;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._rotation = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
-            /**
-             * Scale factor to apply to the gradient.
-             * Default is 1: no scale.
-             */
-            get: function () {
-                return this._scale;
-            },
-            set: function (value) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._scale = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Return a string describing the brush
-         */
-        GradientColorBrush2D.prototype.toString = function () {
-            return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
-        };
-        /**
-         * Build a unique key string for the given parameters
-         */
-        GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
-            return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
-        };
-        GradientColorBrush2D = __decorate([
-            BABYLON.className("GradientColorBrush2D")
-        ], GradientColorBrush2D);
-        return GradientColorBrush2D;
-    }(LockableBase));
-    BABYLON.GradientColorBrush2D = GradientColorBrush2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.brushes2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Base class implementing the ILocable interface.
+     * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
+     */
+    var LockableBase = (function () {
+        function LockableBase() {
+        }
+        LockableBase.prototype.isLocked = function () {
+            return this._isLocked;
+        };
+        LockableBase.prototype.lock = function () {
+            if (this._isLocked) {
+                return true;
+            }
+            this.onLock();
+            this._isLocked = true;
+            return false;
+        };
+        /**
+         * Protected handler that will be called when the instance is about to be locked.
+         */
+        LockableBase.prototype.onLock = function () {
+        };
+        return LockableBase;
+    })();
+    BABYLON.LockableBase = LockableBase;
+    var SolidColorBrush2D = (function (_super) {
+        __extends(SolidColorBrush2D, _super);
+        function SolidColorBrush2D(color, lock) {
+            if (lock === void 0) { lock = false; }
+            _super.call(this);
+            this._color = color;
+            if (lock) {
+                {
+                    this.lock();
+                }
+            }
+        }
+        /**
+         * Return true if the brush is transparent, false if it's totally opaque
+         */
+        SolidColorBrush2D.prototype.isTransparent = function () {
+            return this._color && this._color.a < 1.0;
+        };
+        Object.defineProperty(SolidColorBrush2D.prototype, "color", {
+            /**
+             * The color used by this instance to render
+             * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
+             */
+            get: function () {
+                return this._color;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
+         */
+        SolidColorBrush2D.prototype.toString = function () {
+            return this._color.toHexString();
+        };
+        SolidColorBrush2D = __decorate([
+            BABYLON.className("SolidColorBrush2D")
+        ], SolidColorBrush2D);
+        return SolidColorBrush2D;
+    })(LockableBase);
+    BABYLON.SolidColorBrush2D = SolidColorBrush2D;
+    var GradientColorBrush2D = (function (_super) {
+        __extends(GradientColorBrush2D, _super);
+        function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
+            if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
+            if (rotation === void 0) { rotation = 0; }
+            if (scale === void 0) { scale = 1; }
+            if (lock === void 0) { lock = false; }
+            _super.call(this);
+            this._color1 = color1;
+            this._color2 = color2;
+            this._translation = translation;
+            this._rotation = rotation;
+            this._scale = scale;
+            if (lock) {
+                this.lock();
+            }
+        }
+        /**
+         * Return true if the brush is transparent, false if it's totally opaque
+         */
+        GradientColorBrush2D.prototype.isTransparent = function () {
+            return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
+        };
+        Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
+            /**
+             * First color, the blend will start from this color
+             */
+            get: function () {
+                return this._color1;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color1 = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
+            /**
+             * Second color, the blend will end to this color
+             */
+            get: function () {
+                return this._color2;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._color2 = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
+            /**
+             * Translation vector to apply on the blend
+             * Default is [0;0]
+             */
+            get: function () {
+                return this._translation;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._translation = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
+            /**
+             * Rotation in radian to apply to the brush
+             * Default direction of the brush is vertical, you can change this using this property.
+             * Default is 0.
+             */
+            get: function () {
+                return this._rotation;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._rotation = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
+            /**
+             * Scale factor to apply to the gradient.
+             * Default is 1: no scale.
+             */
+            get: function () {
+                return this._scale;
+            },
+            set: function (value) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._scale = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Return a string describing the brush
+         */
+        GradientColorBrush2D.prototype.toString = function () {
+            return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
+        };
+        /**
+         * Build a unique key string for the given parameters
+         */
+        GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
+            return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
+        };
+        GradientColorBrush2D = __decorate([
+            BABYLON.className("GradientColorBrush2D")
+        ], GradientColorBrush2D);
+        return GradientColorBrush2D;
+    })(LockableBase);
+    BABYLON.GradientColorBrush2D = GradientColorBrush2D;
+})(BABYLON || (BABYLON = {}));

Plik diff jest za duży
+ 1489 - 1490
src/Canvas2d/babylon.canvas2d.js


+ 174 - 175
src/Canvas2d/babylon.canvas2dLayoutEngine.js

@@ -1,175 +1,174 @@
-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 LayoutEngineBase = (function () {
-        function LayoutEngineBase() {
-            this.layoutDirtyOnPropertyChangedMask = 0;
-        }
-        LayoutEngineBase.prototype.updateLayout = function (prim) {
-        };
-        Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        LayoutEngineBase.prototype.isLocked = function () {
-            return this._isLocked;
-        };
-        LayoutEngineBase.prototype.lock = function () {
-            if (this._isLocked) {
-                return false;
-            }
-            this._isLocked = true;
-            return true;
-        };
-        LayoutEngineBase = __decorate([
-            BABYLON.className("LayoutEngineBase")
-        ], LayoutEngineBase);
-        return LayoutEngineBase;
-    }());
-    BABYLON.LayoutEngineBase = LayoutEngineBase;
-    var CanvasLayoutEngine = (function (_super) {
-        __extends(CanvasLayoutEngine, _super);
-        function CanvasLayoutEngine() {
-            _super.apply(this, arguments);
-        }
-        // A very simple (no) layout computing...
-        // The Canvas and its direct children gets the Canvas' size as Layout Area
-        // Indirect children have their Layout Area to the actualSize (margin area) of their parent
-        CanvasLayoutEngine.prototype.updateLayout = function (prim) {
-            // If this prim is layoutDiry we update  its layoutArea and also the one of its direct children
-            if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
-                for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
-                    var child = _a[_i];
-                    this._doUpdate(child);
-                }
-                prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
-            }
-        };
-        CanvasLayoutEngine.prototype._doUpdate = function (prim) {
-            // Canvas ?
-            if (prim instanceof BABYLON.Canvas2D) {
-                prim.layoutArea = prim.actualSize;
-            }
-            else if (prim.parent instanceof BABYLON.Canvas2D) {
-                prim.layoutArea = prim.owner.actualSize;
-            }
-            else {
-                prim.layoutArea = prim.parent.contentArea;
-            }
-        };
-        Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
-        CanvasLayoutEngine = __decorate([
-            BABYLON.className("CanvasLayoutEngine")
-        ], CanvasLayoutEngine);
-        return CanvasLayoutEngine;
-    }(LayoutEngineBase));
-    BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
-    var StackPanelLayoutEngine = (function (_super) {
-        __extends(StackPanelLayoutEngine, _super);
-        function StackPanelLayoutEngine() {
-            _super.call(this);
-            this._isHorizontal = true;
-            this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
-        }
-        Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
-            get: function () {
-                if (!StackPanelLayoutEngine._horizontal) {
-                    StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
-                    StackPanelLayoutEngine._horizontal.isHorizontal = true;
-                    StackPanelLayoutEngine._horizontal.lock();
-                }
-                return StackPanelLayoutEngine._horizontal;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
-            get: function () {
-                if (!StackPanelLayoutEngine._vertical) {
-                    StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
-                    StackPanelLayoutEngine._vertical.isHorizontal = false;
-                    StackPanelLayoutEngine._vertical.lock();
-                }
-                return StackPanelLayoutEngine._vertical;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
-            get: function () {
-                return this._isHorizontal;
-            },
-            set: function (val) {
-                if (this.isLocked()) {
-                    return;
-                }
-                this._isHorizontal = val;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
-            if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
-                var x = 0;
-                var y = 0;
-                var h = this.isHorizontal;
-                var max = 0;
-                for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
-                    var child = _a[_i];
-                    var layoutArea = child.layoutArea;
-                    child.margin.computeArea(child.actualSize, layoutArea);
-                    max = Math.max(max, h ? layoutArea.height : layoutArea.width);
-                }
-                for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
-                    var child = _c[_b];
-                    child.layoutAreaPos = new BABYLON.Vector2(x, y);
-                    var layoutArea = child.layoutArea;
-                    if (h) {
-                        x += layoutArea.width;
-                        child.layoutArea = new BABYLON.Size(layoutArea.width, max);
-                    }
-                    else {
-                        y += layoutArea.height;
-                        child.layoutArea = new BABYLON.Size(max, layoutArea.height);
-                    }
-                }
-                prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
-            }
-        };
-        Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        StackPanelLayoutEngine._horizontal = null;
-        StackPanelLayoutEngine._vertical = null;
-        StackPanelLayoutEngine = __decorate([
-            BABYLON.className("StackPanelLayoutEngine")
-        ], StackPanelLayoutEngine);
-        return StackPanelLayoutEngine;
-    }(LayoutEngineBase));
-    BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var LayoutEngineBase = (function () {
+        function LayoutEngineBase() {
+            this.layoutDirtyOnPropertyChangedMask = 0;
+        }
+        LayoutEngineBase.prototype.updateLayout = function (prim) {
+        };
+        Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        LayoutEngineBase.prototype.isLocked = function () {
+            return this._isLocked;
+        };
+        LayoutEngineBase.prototype.lock = function () {
+            if (this._isLocked) {
+                return false;
+            }
+            this._isLocked = true;
+            return true;
+        };
+        LayoutEngineBase = __decorate([
+            BABYLON.className("LayoutEngineBase")
+        ], LayoutEngineBase);
+        return LayoutEngineBase;
+    })();
+    BABYLON.LayoutEngineBase = LayoutEngineBase;
+    var CanvasLayoutEngine = (function (_super) {
+        __extends(CanvasLayoutEngine, _super);
+        function CanvasLayoutEngine() {
+            _super.apply(this, arguments);
+        }
+        // A very simple (no) layout computing...
+        // The Canvas and its direct children gets the Canvas' size as Layout Area
+        // Indirect children have their Layout Area to the actualSize (margin area) of their parent
+        CanvasLayoutEngine.prototype.updateLayout = function (prim) {
+            // If this prim is layoutDiry we update  its layoutArea and also the one of its direct children
+            if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
+                for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
+                    var child = _a[_i];
+                    this._doUpdate(child);
+                }
+                prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
+            }
+        };
+        CanvasLayoutEngine.prototype._doUpdate = function (prim) {
+            // Canvas ?
+            if (prim instanceof BABYLON.Canvas2D) {
+                prim.layoutArea = prim.actualSize;
+            }
+            else if (prim.parent instanceof BABYLON.Canvas2D) {
+                prim.layoutArea = prim.owner.actualSize;
+            }
+            else {
+                prim.layoutArea = prim.parent.contentArea;
+            }
+        };
+        Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
+        CanvasLayoutEngine = __decorate([
+            BABYLON.className("CanvasLayoutEngine")
+        ], CanvasLayoutEngine);
+        return CanvasLayoutEngine;
+    })(LayoutEngineBase);
+    BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
+    var StackPanelLayoutEngine = (function (_super) {
+        __extends(StackPanelLayoutEngine, _super);
+        function StackPanelLayoutEngine() {
+            _super.call(this);
+            this._isHorizontal = true;
+            this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
+        }
+        Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
+            get: function () {
+                if (!StackPanelLayoutEngine._horizontal) {
+                    StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
+                    StackPanelLayoutEngine._horizontal.isHorizontal = true;
+                    StackPanelLayoutEngine._horizontal.lock();
+                }
+                return StackPanelLayoutEngine._horizontal;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
+            get: function () {
+                if (!StackPanelLayoutEngine._vertical) {
+                    StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
+                    StackPanelLayoutEngine._vertical.isHorizontal = false;
+                    StackPanelLayoutEngine._vertical.lock();
+                }
+                return StackPanelLayoutEngine._vertical;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
+            get: function () {
+                return this._isHorizontal;
+            },
+            set: function (val) {
+                if (this.isLocked()) {
+                    return;
+                }
+                this._isHorizontal = val;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
+            if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
+                var x = 0;
+                var y = 0;
+                var h = this.isHorizontal;
+                var max = 0;
+                for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
+                    var child = _a[_i];
+                    var layoutArea = child.layoutArea;
+                    child.margin.computeArea(child.actualSize, layoutArea);
+                    max = Math.max(max, h ? layoutArea.height : layoutArea.width);
+                }
+                for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
+                    var child = _c[_b];
+                    child.layoutAreaPos = new BABYLON.Vector2(x, y);
+                    var layoutArea = child.layoutArea;
+                    if (h) {
+                        x += layoutArea.width;
+                        child.layoutArea = new BABYLON.Size(layoutArea.width, max);
+                    }
+                    else {
+                        y += layoutArea.height;
+                        child.layoutArea = new BABYLON.Size(max, layoutArea.height);
+                    }
+                }
+                prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
+            }
+        };
+        Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        StackPanelLayoutEngine._horizontal = null;
+        StackPanelLayoutEngine._vertical = null;
+        StackPanelLayoutEngine = __decorate([
+            BABYLON.className("StackPanelLayoutEngine")
+        ], StackPanelLayoutEngine);
+        return StackPanelLayoutEngine;
+    })(LayoutEngineBase);
+    BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
+})(BABYLON || (BABYLON = {}));

+ 353 - 354
src/Canvas2d/babylon.ellipse2d.js

@@ -1,354 +1,353 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Ellipse2DRenderCache = (function (_super) {
-        __extends(Ellipse2DRenderCache, _super);
-        function Ellipse2DRenderCache(engine, modelKey) {
-            _super.call(this, engine, modelKey);
-            this.effectsReady = false;
-            this.fillVB = null;
-            this.fillIB = null;
-            this.fillIndicesCount = 0;
-            this.instancingFillAttributes = null;
-            this.effectFillInstanced = null;
-            this.effectFill = null;
-            this.borderVB = null;
-            this.borderIB = null;
-            this.borderIndicesCount = 0;
-            this.instancingBorderAttributes = null;
-            this.effectBorderInstanced = null;
-            this.effectBorder = null;
-        }
-        Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
-                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            var canvas = instanceInfo.owner.owner;
-            var engine = canvas.engine;
-            var depthFunction = 0;
-            if (this.effectFill && this.effectBorder) {
-                depthFunction = engine.getDepthFunction();
-                engine.setDepthFunctionToLessOrEqual();
-            }
-            var curAlphaMode = engine.getAlphaMode();
-            if (this.effectFill) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-                }
-                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingFillAttributes) {
-                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
-                    }
-                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
-                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                    canvas._addDrawCallCount(1, context.renderMode);
-                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
-                    engine.draw(true, 0, this.fillIndicesCount, count);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.fillIndicesCount);
-                    }
-                }
-            }
-            if (this.effectBorder) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-                }
-                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingBorderAttributes) {
-                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
-                    }
-                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
-                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                    canvas._addDrawCallCount(1, context.renderMode);
-                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
-                    engine.draw(true, 0, this.borderIndicesCount, count);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.borderIndicesCount);
-                    }
-                }
-            }
-            engine.setAlphaMode(curAlphaMode, true);
-            if (this.effectFill && this.effectBorder) {
-                engine.setDepthFunction(depthFunction);
-            }
-            return true;
-        };
-        Ellipse2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.fillVB) {
-                this._engine._releaseBuffer(this.fillVB);
-                this.fillVB = null;
-            }
-            if (this.fillIB) {
-                this._engine._releaseBuffer(this.fillIB);
-                this.fillIB = null;
-            }
-            this.effectFill = null;
-            this.effectFillInstanced = null;
-            this.effectBorder = null;
-            this.effectBorderInstanced = null;
-            if (this.borderVB) {
-                this._engine._releaseBuffer(this.borderVB);
-                this.borderVB = null;
-            }
-            if (this.borderIB) {
-                this._engine._releaseBuffer(this.borderIB);
-                this.borderIB = null;
-            }
-            return true;
-        };
-        return Ellipse2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
-    var Ellipse2DInstanceData = (function (_super) {
-        __extends(Ellipse2DInstanceData, _super);
-        function Ellipse2DInstanceData(partId) {
-            _super.call(this, partId, 1);
-        }
-        Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Ellipse2DInstanceData.prototype, "properties", null);
-        return Ellipse2DInstanceData;
-    }(BABYLON.Shape2DInstanceData));
-    BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
-    var Ellipse2D = (function (_super) {
-        __extends(Ellipse2D, _super);
-        /**
-         * Create an Ellipse 2D Shape primitive
-         * @param settings a combination of settings, possible ones are
-         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
-         * - children: an array of direct children
-         * - id: a text identifier, for information purpose
-         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
-         * - rotation: the initial rotation (in radian) of the primitive. default is 0
-         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
-         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
-         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
-         * - zOrder: override the zOrder with the specified value
-         * - origin: define the normalized origin point location, default [0.5;0.5]
-         * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
-         * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
-         * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
-         * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
-         * - borderThickness: the thickness of the drawn border, default is 1.
-         * - isVisible: true if the group must be visible, false for hidden. Default is true.
-         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
-         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
-         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
-         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
-         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
-         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
-         */
-        function Ellipse2D(settings) {
-            // Avoid checking every time if the object exists
-            if (settings == null) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            if (settings.size != null) {
-                this.size = settings.size;
-            }
-            else if (settings.width || settings.height) {
-                var size = new BABYLON.Size(settings.width, settings.height);
-                this.size = size;
-            }
-            var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
-            this.subdivisions = sub;
-        }
-        Object.defineProperty(Ellipse2D.prototype, "actualSize", {
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this.size;
-            },
-            set: function (value) {
-                this._actualSize = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
-            get: function () {
-                return this._subdivisions;
-            },
-            set: function (value) {
-                this._subdivisions = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
-            var w = this.size.width / 2;
-            var h = this.size.height / 2;
-            var x = intersectInfo._localPickPosition.x - w;
-            var y = intersectInfo._localPickPosition.y - h;
-            return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
-        };
-        Ellipse2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
-        };
-        Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            // Need to create WebGL resources for fill part?
-            if (this.fill) {
-                var vbSize = this.subdivisions + 1;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.fillVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize - 1;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < triCount; i++) {
-                    ib[i * 3 + 0] = 0;
-                    ib[i * 3 + 2] = i + 1;
-                    ib[i * 3 + 1] = i + 2;
-                }
-                ib[triCount * 3 - 2] = 1;
-                renderCache.fillIB = engine.createIndexBuffer(ib);
-                renderCache.fillIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
-                if (ei) {
-                    renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
-                renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            // Need to create WebGL resource for border part?
-            if (this.border) {
-                var vbSize = this.subdivisions * 2;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.borderVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize;
-                var rs = triCount / 2;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < rs; i++) {
-                    var r0 = i;
-                    var r1 = (i + 1) % rs;
-                    ib[i * 6 + 0] = rs + r1;
-                    ib[i * 6 + 1] = rs + r0;
-                    ib[i * 6 + 2] = r0;
-                    ib[i * 6 + 3] = r1;
-                    ib[i * 6 + 4] = rs + r1;
-                    ib[i * 6 + 5] = r0;
-                }
-                renderCache.borderIB = engine.createIndexBuffer(ib);
-                renderCache.borderIndicesCount = (triCount * 3);
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
-                if (ei) {
-                    renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
-                renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            return renderCache;
-        };
-        Ellipse2D.prototype.createInstanceDataParts = function () {
-            var res = new Array();
-            if (this.border) {
-                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
-            }
-            if (this.fill) {
-                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
-            }
-            return res;
-        };
-        Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                var s = this.actualScale;
-                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
-            }
-            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                var s = this.actualScale;
-                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
-            }
-            return true;
-        };
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
-        ], Ellipse2D.prototype, "actualSize", null);
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
-        ], Ellipse2D.prototype, "subdivisions", null);
-        Ellipse2D = __decorate([
-            BABYLON.className("Ellipse2D")
-        ], Ellipse2D);
-        return Ellipse2D;
-    }(BABYLON.Shape2D));
-    BABYLON.Ellipse2D = Ellipse2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.ellipse2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Ellipse2DRenderCache = (function (_super) {
+        __extends(Ellipse2DRenderCache, _super);
+        function Ellipse2DRenderCache(engine, modelKey) {
+            _super.call(this, engine, modelKey);
+            this.effectsReady = false;
+            this.fillVB = null;
+            this.fillIB = null;
+            this.fillIndicesCount = 0;
+            this.instancingFillAttributes = null;
+            this.effectFillInstanced = null;
+            this.effectFill = null;
+            this.borderVB = null;
+            this.borderIB = null;
+            this.borderIndicesCount = 0;
+            this.instancingBorderAttributes = null;
+            this.effectBorderInstanced = null;
+            this.effectBorder = null;
+        }
+        Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
+                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            var canvas = instanceInfo.owner.owner;
+            var engine = canvas.engine;
+            var depthFunction = 0;
+            if (this.effectFill && this.effectBorder) {
+                depthFunction = engine.getDepthFunction();
+                engine.setDepthFunctionToLessOrEqual();
+            }
+            var curAlphaMode = engine.getAlphaMode();
+            if (this.effectFill) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+                }
+                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingFillAttributes) {
+                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
+                    }
+                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
+                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                    canvas._addDrawCallCount(1, context.renderMode);
+                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
+                    engine.draw(true, 0, this.fillIndicesCount, count);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.fillIndicesCount);
+                    }
+                }
+            }
+            if (this.effectBorder) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+                }
+                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingBorderAttributes) {
+                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
+                    }
+                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
+                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                    canvas._addDrawCallCount(1, context.renderMode);
+                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
+                    engine.draw(true, 0, this.borderIndicesCount, count);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.borderIndicesCount);
+                    }
+                }
+            }
+            engine.setAlphaMode(curAlphaMode, true);
+            if (this.effectFill && this.effectBorder) {
+                engine.setDepthFunction(depthFunction);
+            }
+            return true;
+        };
+        Ellipse2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.fillVB) {
+                this._engine._releaseBuffer(this.fillVB);
+                this.fillVB = null;
+            }
+            if (this.fillIB) {
+                this._engine._releaseBuffer(this.fillIB);
+                this.fillIB = null;
+            }
+            this.effectFill = null;
+            this.effectFillInstanced = null;
+            this.effectBorder = null;
+            this.effectBorderInstanced = null;
+            if (this.borderVB) {
+                this._engine._releaseBuffer(this.borderVB);
+                this.borderVB = null;
+            }
+            if (this.borderIB) {
+                this._engine._releaseBuffer(this.borderIB);
+                this.borderIB = null;
+            }
+            return true;
+        };
+        return Ellipse2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
+    var Ellipse2DInstanceData = (function (_super) {
+        __extends(Ellipse2DInstanceData, _super);
+        function Ellipse2DInstanceData(partId) {
+            _super.call(this, partId, 1);
+        }
+        Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Ellipse2DInstanceData.prototype, "properties", null);
+        return Ellipse2DInstanceData;
+    })(BABYLON.Shape2DInstanceData);
+    BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
+    var Ellipse2D = (function (_super) {
+        __extends(Ellipse2D, _super);
+        /**
+         * Create an Ellipse 2D Shape primitive
+         * @param settings a combination of settings, possible ones are
+         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
+         * - children: an array of direct children
+         * - id: a text identifier, for information purpose
+         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
+         * - rotation: the initial rotation (in radian) of the primitive. default is 0
+         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
+         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
+         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
+         * - zOrder: override the zOrder with the specified value
+         * - origin: define the normalized origin point location, default [0.5;0.5]
+         * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
+         * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
+         * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
+         * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
+         * - borderThickness: the thickness of the drawn border, default is 1.
+         * - isVisible: true if the group must be visible, false for hidden. Default is true.
+         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
+         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
+         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
+         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
+         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
+         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
+         */
+        function Ellipse2D(settings) {
+            // Avoid checking every time if the object exists
+            if (settings == null) {
+                settings = {};
+            }
+            _super.call(this, settings);
+            if (settings.size != null) {
+                this.size = settings.size;
+            }
+            else if (settings.width || settings.height) {
+                var size = new BABYLON.Size(settings.width, settings.height);
+                this.size = size;
+            }
+            var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
+            this.subdivisions = sub;
+        }
+        Object.defineProperty(Ellipse2D.prototype, "actualSize", {
+            get: function () {
+                if (this._actualSize) {
+                    return this._actualSize;
+                }
+                return this.size;
+            },
+            set: function (value) {
+                this._actualSize = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
+            get: function () {
+                return this._subdivisions;
+            },
+            set: function (value) {
+                this._subdivisions = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
+            var w = this.size.width / 2;
+            var h = this.size.height / 2;
+            var x = intersectInfo._localPickPosition.x - w;
+            var y = intersectInfo._localPickPosition.y - h;
+            return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
+        };
+        Ellipse2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
+        };
+        Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            // Need to create WebGL resources for fill part?
+            if (this.fill) {
+                var vbSize = this.subdivisions + 1;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.fillVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize - 1;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < triCount; i++) {
+                    ib[i * 3 + 0] = 0;
+                    ib[i * 3 + 2] = i + 1;
+                    ib[i * 3 + 1] = i + 2;
+                }
+                ib[triCount * 3 - 2] = 1;
+                renderCache.fillIB = engine.createIndexBuffer(ib);
+                renderCache.fillIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
+                if (ei) {
+                    renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
+                renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            // Need to create WebGL resource for border part?
+            if (this.border) {
+                var vbSize = this.subdivisions * 2;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.borderVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize;
+                var rs = triCount / 2;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < rs; i++) {
+                    var r0 = i;
+                    var r1 = (i + 1) % rs;
+                    ib[i * 6 + 0] = rs + r1;
+                    ib[i * 6 + 1] = rs + r0;
+                    ib[i * 6 + 2] = r0;
+                    ib[i * 6 + 3] = r1;
+                    ib[i * 6 + 4] = rs + r1;
+                    ib[i * 6 + 5] = r0;
+                }
+                renderCache.borderIB = engine.createIndexBuffer(ib);
+                renderCache.borderIndicesCount = (triCount * 3);
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
+                if (ei) {
+                    renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
+                renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            return renderCache;
+        };
+        Ellipse2D.prototype.createInstanceDataParts = function () {
+            var res = new Array();
+            if (this.border) {
+                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
+            }
+            if (this.fill) {
+                res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
+            }
+            return res;
+        };
+        Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
+                var d = part;
+                var size = this.actualSize;
+                var s = this.actualScale;
+                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
+            }
+            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
+                var d = part;
+                var size = this.actualSize;
+                var s = this.actualScale;
+                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
+            }
+            return true;
+        };
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
+        ], Ellipse2D.prototype, "actualSize", null);
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
+        ], Ellipse2D.prototype, "subdivisions", null);
+        Ellipse2D = __decorate([
+            BABYLON.className("Ellipse2D")
+        ], Ellipse2D);
+        return Ellipse2D;
+    })(BABYLON.Shape2D);
+    BABYLON.Ellipse2D = Ellipse2D;
+})(BABYLON || (BABYLON = {}));

Plik diff jest za duży
+ 927 - 928
src/Canvas2d/babylon.group2d.js


Plik diff jest za duży
+ 1176 - 1177
src/Canvas2d/babylon.lines2d.js


+ 321 - 322
src/Canvas2d/babylon.modelRenderCache.js

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

Plik diff jest za duży
+ 2978 - 2979
src/Canvas2d/babylon.prim2dBase.js


+ 451 - 452
src/Canvas2d/babylon.rectangle2d.js

@@ -1,452 +1,451 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
-    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-    return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var BABYLON;
-(function (BABYLON) {
-    var Rectangle2DRenderCache = (function (_super) {
-        __extends(Rectangle2DRenderCache, _super);
-        function Rectangle2DRenderCache(engine, modelKey) {
-            _super.call(this, engine, modelKey);
-            this.effectsReady = false;
-            this.fillVB = null;
-            this.fillIB = null;
-            this.fillIndicesCount = 0;
-            this.instancingFillAttributes = null;
-            this.effectFill = null;
-            this.effectFillInstanced = null;
-            this.borderVB = null;
-            this.borderIB = null;
-            this.borderIndicesCount = 0;
-            this.instancingBorderAttributes = null;
-            this.effectBorder = null;
-            this.effectBorderInstanced = null;
-        }
-        Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
-                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            var canvas = instanceInfo.owner.owner;
-            var engine = canvas.engine;
-            var depthFunction = 0;
-            if (this.effectFill && this.effectBorder) {
-                depthFunction = engine.getDepthFunction();
-                engine.setDepthFunctionToLessOrEqual();
-            }
-            var curAlphaMode = engine.getAlphaMode();
-            if (this.effectFill) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-                }
-                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingFillAttributes) {
-                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
-                    }
-                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
-                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                    canvas._addDrawCallCount(1, context.renderMode);
-                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
-                    engine.draw(true, 0, this.fillIndicesCount, count);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.fillIndicesCount);
-                    }
-                }
-            }
-            if (this.effectBorder) {
-                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
-                var pid = context.groupInfoPartData[partIndex];
-                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-                }
-                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
-                engine.enableEffect(effect);
-                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
-                if (context.useInstancing) {
-                    if (!this.instancingBorderAttributes) {
-                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
-                    }
-                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
-                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                    canvas._addDrawCallCount(1, context.renderMode);
-                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
-                    engine.draw(true, 0, this.borderIndicesCount, count);
-                    engine.unbindInstanceAttributes();
-                }
-                else {
-                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                        this.setupUniforms(effect, partIndex, pid._partData, i);
-                        engine.draw(true, 0, this.borderIndicesCount);
-                    }
-                }
-            }
-            engine.setAlphaMode(curAlphaMode, true);
-            if (this.effectFill && this.effectBorder) {
-                engine.setDepthFunction(depthFunction);
-            }
-            return true;
-        };
-        Rectangle2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.fillVB) {
-                this._engine._releaseBuffer(this.fillVB);
-                this.fillVB = null;
-            }
-            if (this.fillIB) {
-                this._engine._releaseBuffer(this.fillIB);
-                this.fillIB = null;
-            }
-            this.effectFill = null;
-            this.effectFillInstanced = null;
-            this.effectBorder = null;
-            this.effectBorderInstanced = null;
-            if (this.borderVB) {
-                this._engine._releaseBuffer(this.borderVB);
-                this.borderVB = null;
-            }
-            if (this.borderIB) {
-                this._engine._releaseBuffer(this.borderIB);
-                this.borderIB = null;
-            }
-            return true;
-        };
-        return Rectangle2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
-    var Rectangle2DInstanceData = (function (_super) {
-        __extends(Rectangle2DInstanceData, _super);
-        function Rectangle2DInstanceData(partId) {
-            _super.call(this, partId, 1);
-        }
-        Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Rectangle2DInstanceData.prototype, "properties", null);
-        return Rectangle2DInstanceData;
-    }(BABYLON.Shape2DInstanceData));
-    BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
-    var Rectangle2D = (function (_super) {
-        __extends(Rectangle2D, _super);
-        /**
-         * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
-         * @param settings a combination of settings, possible ones are
-         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
-         * - children: an array of direct children
-         * - id a text identifier, for information purpose
-         * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
-         * - rotation: the initial rotation (in radian) of the primitive. default is 0
-         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
-         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
-         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
-         * - zOrder: override the zOrder with the specified value
-         * - origin: define the normalized origin point location, default [0.5;0.5]
-         * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
-         * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
-         * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
-         * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
-         * - borderThickness: the thickness of the drawn border, default is 1.
-         * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
-         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
-         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
-         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
-         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
-         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
-         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
-         */
-        function Rectangle2D(settings) {
-            // Avoid checking every time if the object exists
-            if (settings == null) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            if (settings.size != null) {
-                this.size = settings.size;
-            }
-            else if (settings.width || settings.height) {
-                var size = new BABYLON.Size(settings.width, settings.height);
-                this.size = size;
-            }
-            //let size            = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
-            var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
-            var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
-            //this.size            = size;
-            this.roundRadius = roundRadius;
-            this.borderThickness = borderThickness;
-        }
-        Object.defineProperty(Rectangle2D.prototype, "actualSize", {
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this.size;
-            },
-            set: function (value) {
-                this._actualSize = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Rectangle2D.prototype, "notRounded", {
-            get: function () {
-                return this._notRounded;
-            },
-            set: function (value) {
-                this._notRounded = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
-            get: function () {
-                return this._roundRadius;
-            },
-            set: function (value) {
-                this._roundRadius = value;
-                this.notRounded = value === 0;
-                this._positioningDirty();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
-            // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
-            if (this.notRounded) {
-                return true;
-            }
-            // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
-            // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
-            // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
-            // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
-            var size = this.size;
-            Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
-            Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
-            var rr = this.roundRadius;
-            var rrs = rr * rr;
-            // Check if the point is in the bottom/left quarter area
-            Rectangle2D._i1.x = rr;
-            Rectangle2D._i1.y = rr;
-            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the top/left quarter area
-            Rectangle2D._i1.x = rr;
-            Rectangle2D._i1.y = size.height - rr;
-            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the top/right quarter area
-            Rectangle2D._i1.x = size.width - rr;
-            Rectangle2D._i1.y = size.height - rr;
-            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // Check if the point is in the bottom/right quarter area
-            Rectangle2D._i1.x = size.width - rr;
-            Rectangle2D._i1.y = rr;
-            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
-                // Compute the intersection point in the quarter local space
-                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
-                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
-                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
-                return Rectangle2D._i2.lengthSquared() <= rrs;
-            }
-            // At any other locations the point is guarantied to be inside
-            return true;
-        };
-        Rectangle2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
-        };
-        Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            // Need to create WebGL resources for fill part?
-            if (this.fill) {
-                var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.fillVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize - 1;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < triCount; i++) {
-                    ib[i * 3 + 0] = 0;
-                    ib[i * 3 + 2] = i + 1;
-                    ib[i * 3 + 1] = i + 2;
-                }
-                ib[triCount * 3 - 2] = 1;
-                renderCache.fillIB = engine.createIndexBuffer(ib);
-                renderCache.fillIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
-                if (ei) {
-                    renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
-                renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            // Need to create WebGL resource for border part?
-            if (this.border) {
-                var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
-                var vb = new Float32Array(vbSize);
-                for (var i = 0; i < vbSize; i++) {
-                    vb[i] = i;
-                }
-                renderCache.borderVB = engine.createVertexBuffer(vb);
-                var triCount = vbSize;
-                var rs = triCount / 2;
-                var ib = new Float32Array(triCount * 3);
-                for (var i = 0; i < rs; i++) {
-                    var r0 = i;
-                    var r1 = (i + 1) % rs;
-                    ib[i * 6 + 0] = rs + r1;
-                    ib[i * 6 + 1] = rs + r0;
-                    ib[i * 6 + 2] = r0;
-                    ib[i * 6 + 3] = r1;
-                    ib[i * 6 + 4] = rs + r1;
-                    ib[i * 6 + 5] = r0;
-                }
-                renderCache.borderIB = engine.createIndexBuffer(ib);
-                renderCache.borderIndicesCount = triCount * 3;
-                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
-                if (ei) {
-                    renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-                }
-                // Get the non instanced version
-                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
-                renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
-            }
-            return renderCache;
-        };
-        // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
-        Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
-            // Fall back to default implementation if there's no round Radius
-            if (this._notRounded) {
-                _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
-            }
-            else {
-                var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
-                initialContentPosition.x = initialContentPosition.y = rr;
-                initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
-                initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
-            }
-        };
-        Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
-            // Fall back to default implementation if there's no round Radius
-            if (this._notRounded) {
-                _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
-            }
-            else {
-                var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
-                newPrimSize.copyFrom(primSize);
-                newPrimSize.width += rr * 2;
-                newPrimSize.height += rr * 2;
-            }
-        };
-        Rectangle2D.prototype.createInstanceDataParts = function () {
-            var res = new Array();
-            if (this.border) {
-                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
-            }
-            if (this.fill) {
-                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
-            }
-            return res;
-        };
-        Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                var s = this.actualScale;
-                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
-            }
-            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
-                var d = part;
-                var size = this.actualSize;
-                var s = this.actualScale;
-                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
-            }
-            return true;
-        };
-        Rectangle2D._i0 = BABYLON.Vector2.Zero();
-        Rectangle2D._i1 = BABYLON.Vector2.Zero();
-        Rectangle2D._i2 = BABYLON.Vector2.Zero();
-        Rectangle2D.roundSubdivisions = 16;
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
-        ], Rectangle2D.prototype, "actualSize", null);
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
-        ], Rectangle2D.prototype, "notRounded", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
-        ], Rectangle2D.prototype, "roundRadius", null);
-        Rectangle2D = __decorate([
-            BABYLON.className("Rectangle2D")
-        ], Rectangle2D);
-        return Rectangle2D;
-    }(BABYLON.Shape2D));
-    BABYLON.Rectangle2D = Rectangle2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.rectangle2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Rectangle2DRenderCache = (function (_super) {
+        __extends(Rectangle2DRenderCache, _super);
+        function Rectangle2DRenderCache(engine, modelKey) {
+            _super.call(this, engine, modelKey);
+            this.effectsReady = false;
+            this.fillVB = null;
+            this.fillIB = null;
+            this.fillIndicesCount = 0;
+            this.instancingFillAttributes = null;
+            this.effectFill = null;
+            this.effectFillInstanced = null;
+            this.borderVB = null;
+            this.borderIB = null;
+            this.borderIndicesCount = 0;
+            this.instancingBorderAttributes = null;
+            this.effectBorder = null;
+            this.effectBorderInstanced = null;
+        }
+        Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
+                    (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            var canvas = instanceInfo.owner.owner;
+            var engine = canvas.engine;
+            var depthFunction = 0;
+            if (this.effectFill && this.effectBorder) {
+                depthFunction = engine.getDepthFunction();
+                engine.setDepthFunctionToLessOrEqual();
+            }
+            var curAlphaMode = engine.getAlphaMode();
+            if (this.effectFill) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+                }
+                var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingFillAttributes) {
+                        this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
+                    }
+                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
+                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                    canvas._addDrawCallCount(1, context.renderMode);
+                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
+                    engine.draw(true, 0, this.fillIndicesCount, count);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.fillIndicesCount);
+                    }
+                }
+            }
+            if (this.effectBorder) {
+                var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
+                var pid = context.groupInfoPartData[partIndex];
+                if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+                }
+                var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
+                engine.enableEffect(effect);
+                engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
+                if (context.useInstancing) {
+                    if (!this.instancingBorderAttributes) {
+                        this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
+                    }
+                    var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
+                    var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                    canvas._addDrawCallCount(1, context.renderMode);
+                    engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
+                    engine.draw(true, 0, this.borderIndicesCount, count);
+                    engine.unbindInstanceAttributes();
+                }
+                else {
+                    canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                    for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                        this.setupUniforms(effect, partIndex, pid._partData, i);
+                        engine.draw(true, 0, this.borderIndicesCount);
+                    }
+                }
+            }
+            engine.setAlphaMode(curAlphaMode, true);
+            if (this.effectFill && this.effectBorder) {
+                engine.setDepthFunction(depthFunction);
+            }
+            return true;
+        };
+        Rectangle2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.fillVB) {
+                this._engine._releaseBuffer(this.fillVB);
+                this.fillVB = null;
+            }
+            if (this.fillIB) {
+                this._engine._releaseBuffer(this.fillIB);
+                this.fillIB = null;
+            }
+            this.effectFill = null;
+            this.effectFillInstanced = null;
+            this.effectBorder = null;
+            this.effectBorderInstanced = null;
+            if (this.borderVB) {
+                this._engine._releaseBuffer(this.borderVB);
+                this.borderVB = null;
+            }
+            if (this.borderIB) {
+                this._engine._releaseBuffer(this.borderIB);
+                this.borderIB = null;
+            }
+            return true;
+        };
+        return Rectangle2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
+    var Rectangle2DInstanceData = (function (_super) {
+        __extends(Rectangle2DInstanceData, _super);
+        function Rectangle2DInstanceData(partId) {
+            _super.call(this, partId, 1);
+        }
+        Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Rectangle2DInstanceData.prototype, "properties", null);
+        return Rectangle2DInstanceData;
+    })(BABYLON.Shape2DInstanceData);
+    BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
+    var Rectangle2D = (function (_super) {
+        __extends(Rectangle2D, _super);
+        /**
+         * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
+         * @param settings a combination of settings, possible ones are
+         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
+         * - children: an array of direct children
+         * - id a text identifier, for information purpose
+         * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
+         * - rotation: the initial rotation (in radian) of the primitive. default is 0
+         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
+         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
+         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
+         * - zOrder: override the zOrder with the specified value
+         * - origin: define the normalized origin point location, default [0.5;0.5]
+         * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
+         * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
+         * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
+         * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
+         * - borderThickness: the thickness of the drawn border, default is 1.
+         * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
+         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
+         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
+         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
+         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
+         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
+         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
+         */
+        function Rectangle2D(settings) {
+            // Avoid checking every time if the object exists
+            if (settings == null) {
+                settings = {};
+            }
+            _super.call(this, settings);
+            if (settings.size != null) {
+                this.size = settings.size;
+            }
+            else if (settings.width || settings.height) {
+                var size = new BABYLON.Size(settings.width, settings.height);
+                this.size = size;
+            }
+            //let size            = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
+            var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
+            var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
+            //this.size            = size;
+            this.roundRadius = roundRadius;
+            this.borderThickness = borderThickness;
+        }
+        Object.defineProperty(Rectangle2D.prototype, "actualSize", {
+            get: function () {
+                if (this._actualSize) {
+                    return this._actualSize;
+                }
+                return this.size;
+            },
+            set: function (value) {
+                this._actualSize = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Rectangle2D.prototype, "notRounded", {
+            get: function () {
+                return this._notRounded;
+            },
+            set: function (value) {
+                this._notRounded = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
+            get: function () {
+                return this._roundRadius;
+            },
+            set: function (value) {
+                this._roundRadius = value;
+                this.notRounded = value === 0;
+                this._positioningDirty();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
+            // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
+            if (this.notRounded) {
+                return true;
+            }
+            // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
+            // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
+            // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
+            // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
+            var size = this.size;
+            Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
+            Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
+            var rr = this.roundRadius;
+            var rrs = rr * rr;
+            // Check if the point is in the bottom/left quarter area
+            Rectangle2D._i1.x = rr;
+            Rectangle2D._i1.y = rr;
+            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the top/left quarter area
+            Rectangle2D._i1.x = rr;
+            Rectangle2D._i1.y = size.height - rr;
+            if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the top/right quarter area
+            Rectangle2D._i1.x = size.width - rr;
+            Rectangle2D._i1.y = size.height - rr;
+            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // Check if the point is in the bottom/right quarter area
+            Rectangle2D._i1.x = size.width - rr;
+            Rectangle2D._i1.y = rr;
+            if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
+                // Compute the intersection point in the quarter local space
+                Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
+                Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
+                // It's a hit if the squared distance is less/equal to the squared radius of the round circle
+                return Rectangle2D._i2.lengthSquared() <= rrs;
+            }
+            // At any other locations the point is guarantied to be inside
+            return true;
+        };
+        Rectangle2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
+        };
+        Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            // Need to create WebGL resources for fill part?
+            if (this.fill) {
+                var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.fillVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize - 1;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < triCount; i++) {
+                    ib[i * 3 + 0] = 0;
+                    ib[i * 3 + 2] = i + 1;
+                    ib[i * 3 + 1] = i + 2;
+                }
+                ib[triCount * 3 - 2] = 1;
+                renderCache.fillIB = engine.createIndexBuffer(ib);
+                renderCache.fillIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
+                if (ei) {
+                    renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
+                renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            // Need to create WebGL resource for border part?
+            if (this.border) {
+                var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
+                var vb = new Float32Array(vbSize);
+                for (var i = 0; i < vbSize; i++) {
+                    vb[i] = i;
+                }
+                renderCache.borderVB = engine.createVertexBuffer(vb);
+                var triCount = vbSize;
+                var rs = triCount / 2;
+                var ib = new Float32Array(triCount * 3);
+                for (var i = 0; i < rs; i++) {
+                    var r0 = i;
+                    var r1 = (i + 1) % rs;
+                    ib[i * 6 + 0] = rs + r1;
+                    ib[i * 6 + 1] = rs + r0;
+                    ib[i * 6 + 2] = r0;
+                    ib[i * 6 + 3] = r1;
+                    ib[i * 6 + 4] = rs + r1;
+                    ib[i * 6 + 5] = r0;
+                }
+                renderCache.borderIB = engine.createIndexBuffer(ib);
+                renderCache.borderIndicesCount = triCount * 3;
+                // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+                var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
+                if (ei) {
+                    renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+                }
+                // Get the non instanced version
+                ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
+                renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
+            }
+            return renderCache;
+        };
+        // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
+        Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
+            // Fall back to default implementation if there's no round Radius
+            if (this._notRounded) {
+                _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
+            }
+            else {
+                var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
+                initialContentPosition.x = initialContentPosition.y = rr;
+                initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
+                initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
+            }
+        };
+        Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
+            // Fall back to default implementation if there's no round Radius
+            if (this._notRounded) {
+                _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
+            }
+            else {
+                var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
+                newPrimSize.copyFrom(primSize);
+                newPrimSize.width += rr * 2;
+                newPrimSize.height += rr * 2;
+            }
+        };
+        Rectangle2D.prototype.createInstanceDataParts = function () {
+            var res = new Array();
+            if (this.border) {
+                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
+            }
+            if (this.fill) {
+                res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
+            }
+            return res;
+        };
+        Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
+                var d = part;
+                var size = this.actualSize;
+                var s = this.actualScale;
+                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
+            }
+            else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
+                var d = part;
+                var size = this.actualSize;
+                var s = this.actualScale;
+                d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
+            }
+            return true;
+        };
+        Rectangle2D._i0 = BABYLON.Vector2.Zero();
+        Rectangle2D._i1 = BABYLON.Vector2.Zero();
+        Rectangle2D._i2 = BABYLON.Vector2.Zero();
+        Rectangle2D.roundSubdivisions = 16;
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
+        ], Rectangle2D.prototype, "actualSize", null);
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
+        ], Rectangle2D.prototype, "notRounded", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
+        ], Rectangle2D.prototype, "roundRadius", null);
+        Rectangle2D = __decorate([
+            BABYLON.className("Rectangle2D")
+        ], Rectangle2D);
+        return Rectangle2D;
+    })(BABYLON.Shape2D);
+    BABYLON.Rectangle2D = Rectangle2D;
+})(BABYLON || (BABYLON = {}));

Plik diff jest za duży
+ 882 - 883
src/Canvas2d/babylon.renderablePrim2d.js


+ 290 - 291
src/Canvas2d/babylon.shape2d.js

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

Plik diff jest za duży
+ 583 - 584
src/Canvas2d/babylon.smartPropertyPrim.js


+ 453 - 454
src/Canvas2d/babylon.sprite2d.js

@@ -1,454 +1,453 @@
-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 Sprite2DRenderCache = (function (_super) {
-        __extends(Sprite2DRenderCache, _super);
-        function Sprite2DRenderCache() {
-            _super.apply(this, arguments);
-            this.effectsReady = false;
-            this.vb = null;
-            this.ib = null;
-            this.instancingAttributes = null;
-            this.texture = null;
-            this.effect = null;
-            this.effectInstanced = null;
-        }
-        Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
-            var canvas = instanceInfo.owner.owner;
-            var engine = canvas.engine;
-            var cur = engine.getAlphaMode();
-            var effect = context.useInstancing ? this.effectInstanced : this.effect;
-            engine.enableEffect(effect);
-            effect.setTexture("diffuseSampler", this.texture);
-            engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
-            if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
-                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-            }
-            effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
-            var pid = context.groupInfoPartData[0];
-            if (context.useInstancing) {
-                if (!this.instancingAttributes) {
-                    this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
-                }
-                var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
-                var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                canvas._addDrawCallCount(1, context.renderMode);
-                engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
-                engine.draw(true, 0, 6, count);
-                engine.unbindInstanceAttributes();
-            }
-            else {
-                canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                    this.setupUniforms(effect, 0, pid._partData, i);
-                    engine.draw(true, 0, 6);
-                }
-            }
-            engine.setAlphaMode(cur, true);
-            return true;
-        };
-        Sprite2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.vb) {
-                this._engine._releaseBuffer(this.vb);
-                this.vb = null;
-            }
-            if (this.ib) {
-                this._engine._releaseBuffer(this.ib);
-                this.ib = null;
-            }
-            //if (this.texture) {
-            //    this.texture.dispose();
-            //    this.texture = null;
-            //}
-            this.effect = null;
-            this.effectInstanced = null;
-            return true;
-        };
-        return Sprite2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
-    var Sprite2DInstanceData = (function (_super) {
-        __extends(Sprite2DInstanceData, _super);
-        function Sprite2DInstanceData(partId) {
-            _super.call(this, partId, 1);
-        }
-        Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
-            // 3 floats being:
-            // - x: frame number to display
-            // - y: invertY setting
-            // - z: alignToPixel setting
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Sprite2DInstanceData.prototype, "topLeftUV", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Sprite2DInstanceData.prototype, "sizeUV", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Sprite2DInstanceData.prototype, "scaleFactor", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Sprite2DInstanceData.prototype, "textureSize", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Sprite2DInstanceData.prototype, "properties", null);
-        return Sprite2DInstanceData;
-    }(BABYLON.InstanceDataBase));
-    BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
-    var Sprite2D = (function (_super) {
-        __extends(Sprite2D, _super);
-        /**
-         * Create an 2D Sprite primitive
-         * @param texture the texture that stores the sprite to render
-         * @param settings a combination of settings, possible ones are
-         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
-         * - children: an array of direct children
-         * - id a text identifier, for information purpose
-         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
-         * - rotation: the initial rotation (in radian) of the primitive. default is 0
-         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
-         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
-         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
-         * - zOrder: override the zOrder with the specified value
-         * - origin: define the normalized origin point location, default [0.5;0.5]
-         * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
-         * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
-         * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
-         * - invertY: if true the texture Y will be inverted, default is false.
-         * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
-         * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
-         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
-         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
-         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
-         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
-         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
-         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
-         */
-        function Sprite2D(texture, settings) {
-            var _this = this;
-            if (!settings) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            this.texture = texture;
-            this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.size = settings.spriteSize;
-            this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
-            this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
-            this.spriteFrame = 0;
-            this.invertY = (settings.invertY == null) ? false : settings.invertY;
-            this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
-            this.useAlphaFromTexture = true;
-            if (settings.spriteSize == null || !texture.isReady()) {
-                if (texture.isReady()) {
-                    this.size = texture.getBaseSize();
-                }
-                else {
-                    texture.onLoadObservable.add(function () {
-                        if (settings.spriteSize == null) {
-                            _this.size = texture.getBaseSize();
-                        }
-                        _this._positioningDirty();
-                        _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
-                    });
-                }
-            }
-        }
-        Object.defineProperty(Sprite2D.prototype, "texture", {
-            get: function () {
-                return this._texture;
-            },
-            set: function (value) {
-                this._texture = value;
-                this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
-            get: function () {
-                return this._useAlphaFromTexture;
-            },
-            set: function (value) {
-                if (this._useAlphaFromTexture === value) {
-                    return;
-                }
-                this._useAlphaFromTexture = value;
-                this._updateRenderMode();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "actualSize", {
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this.size;
-            },
-            set: function (value) {
-                this._actualSize = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
-            get: function () {
-                return this._location;
-            },
-            set: function (value) {
-                this._location = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
-            get: function () {
-                return this._spriteFrame;
-            },
-            set: function (value) {
-                this._spriteFrame = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "invertY", {
-            get: function () {
-                return this._invertY;
-            },
-            set: function (value) {
-                this._invertY = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
-            get: function () {
-                return this._spriteScaleFactor;
-            },
-            set: function (value) {
-                this._spriteScaleFactor = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
-            /**
-             * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
-             */
-            get: function () {
-                return this._alignToPixel;
-            },
-            set: function (value) {
-                this._alignToPixel = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Sprite2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
-        };
-        /**
-         * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
-         */
-        Sprite2D.prototype.getAnimatables = function () {
-            var res = new Array();
-            if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
-                res.push(this.texture);
-            }
-            return res;
-        };
-        Sprite2D.prototype.levelIntersect = function (intersectInfo) {
-            // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
-            return true;
-        };
-        Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
-            var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
-            return sprite;
-        };
-        Sprite2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            var vb = new Float32Array(4);
-            for (var i = 0; i < 4; i++) {
-                vb[i] = i;
-            }
-            renderCache.vb = engine.createVertexBuffer(vb);
-            var ib = new Float32Array(6);
-            ib[0] = 0;
-            ib[1] = 2;
-            ib[2] = 1;
-            ib[3] = 0;
-            ib[4] = 3;
-            ib[5] = 2;
-            renderCache.ib = engine.createIndexBuffer(ib);
-            renderCache.texture = this.texture;
-            // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-            var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
-            if (ei) {
-                renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
-            }
-            ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
-            renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
-            return renderCache;
-        };
-        Sprite2D.prototype.createInstanceDataParts = function () {
-            return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
-        };
-        Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
-            Sprite2D.layoutConstructMode = true;
-        };
-        // if obj contains something, we restore the _text property
-        Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
-            Sprite2D.layoutConstructMode = false;
-        };
-        Sprite2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
-                return false;
-            }
-            if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
-                var d = this._instanceDataParts[0];
-                if (Sprite2D.layoutConstructMode) {
-                    d.topLeftUV = BABYLON.Vector2.Zero();
-                    d.sizeUV = BABYLON.Vector2.Zero();
-                    d.properties = BABYLON.Vector3.Zero();
-                    d.textureSize = BABYLON.Vector2.Zero();
-                    d.scaleFactor = BABYLON.Vector2.Zero();
-                }
-                else {
-                    var ts = this.texture.getBaseSize();
-                    var sl = this.spriteLocation;
-                    var ss = this.actualSize;
-                    var ssf = this.spriteScaleFactor;
-                    d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
-                    var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
-                    d.sizeUV = suv;
-                    d.scaleFactor = ssf;
-                    Sprite2D._prop.x = this.spriteFrame;
-                    Sprite2D._prop.y = this.invertY ? 1 : 0;
-                    Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
-                    d.properties = Sprite2D._prop;
-                    d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
-                }
-            }
-            return true;
-        };
-        Sprite2D.prototype._mustUpdateInstance = function () {
-            var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
-            this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
-            if (res) {
-                this._updateRenderMode();
-            }
-            return res;
-        };
-        Sprite2D.prototype._useTextureAlpha = function () {
-            return this.texture != null && this.texture.hasAlpha;
-        };
-        Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
-            return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
-        };
-        Sprite2D.SPRITE2D_MAINPARTID = 1;
-        Sprite2D._prop = BABYLON.Vector3.Zero();
-        Sprite2D.layoutConstructMode = false;
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
-        ], Sprite2D.prototype, "texture", null);
-        __decorate([
-            BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
-        ], Sprite2D.prototype, "useAlphaFromTexture", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
-        ], Sprite2D.prototype, "actualSize", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
-        ], Sprite2D.prototype, "spriteLocation", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
-        ], Sprite2D.prototype, "spriteFrame", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
-        ], Sprite2D.prototype, "invertY", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
-        ], Sprite2D.prototype, "spriteScaleFactor", null);
-        Sprite2D = __decorate([
-            BABYLON.className("Sprite2D")
-        ], Sprite2D);
-        return Sprite2D;
-    }(BABYLON.RenderablePrim2D));
-    BABYLON.Sprite2D = Sprite2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.sprite2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Sprite2DRenderCache = (function (_super) {
+        __extends(Sprite2DRenderCache, _super);
+        function Sprite2DRenderCache() {
+            _super.apply(this, arguments);
+            this.effectsReady = false;
+            this.vb = null;
+            this.ib = null;
+            this.instancingAttributes = null;
+            this.texture = null;
+            this.effect = null;
+            this.effectInstanced = null;
+        }
+        Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
+            var canvas = instanceInfo.owner.owner;
+            var engine = canvas.engine;
+            var cur = engine.getAlphaMode();
+            var effect = context.useInstancing ? this.effectInstanced : this.effect;
+            engine.enableEffect(effect);
+            effect.setTexture("diffuseSampler", this.texture);
+            engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
+            if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+            }
+            effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
+            var pid = context.groupInfoPartData[0];
+            if (context.useInstancing) {
+                if (!this.instancingAttributes) {
+                    this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
+                }
+                var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
+                var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                canvas._addDrawCallCount(1, context.renderMode);
+                engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
+                engine.draw(true, 0, 6, count);
+                engine.unbindInstanceAttributes();
+            }
+            else {
+                canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                    this.setupUniforms(effect, 0, pid._partData, i);
+                    engine.draw(true, 0, 6);
+                }
+            }
+            engine.setAlphaMode(cur, true);
+            return true;
+        };
+        Sprite2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.vb) {
+                this._engine._releaseBuffer(this.vb);
+                this.vb = null;
+            }
+            if (this.ib) {
+                this._engine._releaseBuffer(this.ib);
+                this.ib = null;
+            }
+            //if (this.texture) {
+            //    this.texture.dispose();
+            //    this.texture = null;
+            //}
+            this.effect = null;
+            this.effectInstanced = null;
+            return true;
+        };
+        return Sprite2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
+    var Sprite2DInstanceData = (function (_super) {
+        __extends(Sprite2DInstanceData, _super);
+        function Sprite2DInstanceData(partId) {
+            _super.call(this, partId, 1);
+        }
+        Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
+            // 3 floats being:
+            // - x: frame number to display
+            // - y: invertY setting
+            // - z: alignToPixel setting
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Sprite2DInstanceData.prototype, "topLeftUV", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Sprite2DInstanceData.prototype, "sizeUV", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Sprite2DInstanceData.prototype, "scaleFactor", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Sprite2DInstanceData.prototype, "textureSize", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Sprite2DInstanceData.prototype, "properties", null);
+        return Sprite2DInstanceData;
+    })(BABYLON.InstanceDataBase);
+    BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
+    var Sprite2D = (function (_super) {
+        __extends(Sprite2D, _super);
+        /**
+         * Create an 2D Sprite primitive
+         * @param texture the texture that stores the sprite to render
+         * @param settings a combination of settings, possible ones are
+         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
+         * - children: an array of direct children
+         * - id a text identifier, for information purpose
+         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
+         * - rotation: the initial rotation (in radian) of the primitive. default is 0
+         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
+         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
+         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
+         * - zOrder: override the zOrder with the specified value
+         * - origin: define the normalized origin point location, default [0.5;0.5]
+         * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
+         * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
+         * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
+         * - invertY: if true the texture Y will be inverted, default is false.
+         * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
+         * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
+         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
+         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
+         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
+         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
+         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
+         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
+         */
+        function Sprite2D(texture, settings) {
+            var _this = this;
+            if (!settings) {
+                settings = {};
+            }
+            _super.call(this, settings);
+            this.texture = texture;
+            this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.size = settings.spriteSize;
+            this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
+            this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
+            this.spriteFrame = 0;
+            this.invertY = (settings.invertY == null) ? false : settings.invertY;
+            this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
+            this.useAlphaFromTexture = true;
+            if (settings.spriteSize == null || !texture.isReady()) {
+                if (texture.isReady()) {
+                    this.size = texture.getBaseSize();
+                }
+                else {
+                    texture.onLoadObservable.add(function () {
+                        if (settings.spriteSize == null) {
+                            _this.size = texture.getBaseSize();
+                        }
+                        _this._positioningDirty();
+                        _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
+                    });
+                }
+            }
+        }
+        Object.defineProperty(Sprite2D.prototype, "texture", {
+            get: function () {
+                return this._texture;
+            },
+            set: function (value) {
+                this._texture = value;
+                this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
+            get: function () {
+                return this._useAlphaFromTexture;
+            },
+            set: function (value) {
+                if (this._useAlphaFromTexture === value) {
+                    return;
+                }
+                this._useAlphaFromTexture = value;
+                this._updateRenderMode();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "actualSize", {
+            get: function () {
+                if (this._actualSize) {
+                    return this._actualSize;
+                }
+                return this.size;
+            },
+            set: function (value) {
+                this._actualSize = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
+            get: function () {
+                return this._location;
+            },
+            set: function (value) {
+                this._location = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
+            get: function () {
+                return this._spriteFrame;
+            },
+            set: function (value) {
+                this._spriteFrame = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "invertY", {
+            get: function () {
+                return this._invertY;
+            },
+            set: function (value) {
+                this._invertY = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
+            get: function () {
+                return this._spriteScaleFactor;
+            },
+            set: function (value) {
+                this._spriteScaleFactor = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
+            /**
+             * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
+             */
+            get: function () {
+                return this._alignToPixel;
+            },
+            set: function (value) {
+                this._alignToPixel = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Sprite2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
+        };
+        /**
+         * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
+         */
+        Sprite2D.prototype.getAnimatables = function () {
+            var res = new Array();
+            if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
+                res.push(this.texture);
+            }
+            return res;
+        };
+        Sprite2D.prototype.levelIntersect = function (intersectInfo) {
+            // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
+            return true;
+        };
+        Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
+            var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
+            return sprite;
+        };
+        Sprite2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            var vb = new Float32Array(4);
+            for (var i = 0; i < 4; i++) {
+                vb[i] = i;
+            }
+            renderCache.vb = engine.createVertexBuffer(vb);
+            var ib = new Float32Array(6);
+            ib[0] = 0;
+            ib[1] = 2;
+            ib[2] = 1;
+            ib[3] = 0;
+            ib[4] = 3;
+            ib[5] = 2;
+            renderCache.ib = engine.createIndexBuffer(ib);
+            renderCache.texture = this.texture;
+            // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+            var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
+            if (ei) {
+                renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
+            }
+            ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
+            renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
+            return renderCache;
+        };
+        Sprite2D.prototype.createInstanceDataParts = function () {
+            return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
+        };
+        Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
+            Sprite2D.layoutConstructMode = true;
+        };
+        // if obj contains something, we restore the _text property
+        Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
+            Sprite2D.layoutConstructMode = false;
+        };
+        Sprite2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
+                return false;
+            }
+            if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
+                var d = this._instanceDataParts[0];
+                if (Sprite2D.layoutConstructMode) {
+                    d.topLeftUV = BABYLON.Vector2.Zero();
+                    d.sizeUV = BABYLON.Vector2.Zero();
+                    d.properties = BABYLON.Vector3.Zero();
+                    d.textureSize = BABYLON.Vector2.Zero();
+                    d.scaleFactor = BABYLON.Vector2.Zero();
+                }
+                else {
+                    var ts = this.texture.getBaseSize();
+                    var sl = this.spriteLocation;
+                    var ss = this.actualSize;
+                    var ssf = this.spriteScaleFactor;
+                    d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
+                    var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
+                    d.sizeUV = suv;
+                    d.scaleFactor = ssf;
+                    Sprite2D._prop.x = this.spriteFrame;
+                    Sprite2D._prop.y = this.invertY ? 1 : 0;
+                    Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
+                    d.properties = Sprite2D._prop;
+                    d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
+                }
+            }
+            return true;
+        };
+        Sprite2D.prototype._mustUpdateInstance = function () {
+            var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
+            this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
+            if (res) {
+                this._updateRenderMode();
+            }
+            return res;
+        };
+        Sprite2D.prototype._useTextureAlpha = function () {
+            return this.texture != null && this.texture.hasAlpha;
+        };
+        Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
+            return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
+        };
+        Sprite2D.SPRITE2D_MAINPARTID = 1;
+        Sprite2D._prop = BABYLON.Vector3.Zero();
+        Sprite2D.layoutConstructMode = false;
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
+        ], Sprite2D.prototype, "texture", null);
+        __decorate([
+            BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
+        ], Sprite2D.prototype, "useAlphaFromTexture", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
+        ], Sprite2D.prototype, "actualSize", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
+        ], Sprite2D.prototype, "spriteLocation", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
+        ], Sprite2D.prototype, "spriteFrame", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
+        ], Sprite2D.prototype, "invertY", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
+        ], Sprite2D.prototype, "spriteScaleFactor", null);
+        Sprite2D = __decorate([
+            BABYLON.className("Sprite2D")
+        ], Sprite2D);
+        return Sprite2D;
+    })(BABYLON.RenderablePrim2D);
+    BABYLON.Sprite2D = Sprite2D;
+})(BABYLON || (BABYLON = {}));

+ 453 - 454
src/Canvas2d/babylon.text2d.js

@@ -1,454 +1,453 @@
-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 Text2DRenderCache = (function (_super) {
-        __extends(Text2DRenderCache, _super);
-        function Text2DRenderCache() {
-            _super.apply(this, arguments);
-            this.effectsReady = false;
-            this.vb = null;
-            this.ib = null;
-            this.instancingAttributes = null;
-            this.fontTexture = null;
-            this.effect = null;
-            this.effectInstanced = null;
-        }
-        Text2DRenderCache.prototype.render = function (instanceInfo, context) {
-            // Do nothing if the shader is still loading/preparing 
-            if (!this.effectsReady) {
-                if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
-                    return false;
-                }
-                this.effectsReady = true;
-            }
-            var canvas = instanceInfo.owner.owner;
-            var engine = canvas.engine;
-            this.fontTexture.update();
-            var effect = context.useInstancing ? this.effectInstanced : this.effect;
-            engine.enableEffect(effect);
-            effect.setTexture("diffuseSampler", this.fontTexture);
-            engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
-            var curAlphaMode = engine.getAlphaMode();
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
-            var pid = context.groupInfoPartData[0];
-            if (context.useInstancing) {
-                if (!this.instancingAttributes) {
-                    this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
-                }
-                var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
-                var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
-                canvas._addDrawCallCount(1, context.renderMode);
-                engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
-                engine.draw(true, 0, 6, count);
-                engine.unbindInstanceAttributes();
-            }
-            else {
-                canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
-                for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
-                    this.setupUniforms(effect, 0, pid._partData, i);
-                    engine.draw(true, 0, 6);
-                }
-            }
-            engine.setAlphaMode(curAlphaMode, true);
-            return true;
-        };
-        Text2DRenderCache.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this.vb) {
-                this._engine._releaseBuffer(this.vb);
-                this.vb = null;
-            }
-            if (this.ib) {
-                this._engine._releaseBuffer(this.ib);
-                this.ib = null;
-            }
-            if (this.fontTexture) {
-                this.fontTexture.decCachedFontTextureCounter();
-                this.fontTexture = null;
-            }
-            this.effect = null;
-            this.effectInstanced = null;
-            return true;
-        };
-        return Text2DRenderCache;
-    }(BABYLON.ModelRenderCache));
-    BABYLON.Text2DRenderCache = Text2DRenderCache;
-    var Text2DInstanceData = (function (_super) {
-        __extends(Text2DInstanceData, _super);
-        function Text2DInstanceData(partId, dataElementCount) {
-            _super.call(this, partId, dataElementCount);
-        }
-        Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2DInstanceData.prototype, "color", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
-            get: function () {
-                return null;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        __decorate([
-            BABYLON.instanceData()
-        ], Text2DInstanceData.prototype, "topLeftUV", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Text2DInstanceData.prototype, "sizeUV", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Text2DInstanceData.prototype, "textureSize", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Text2DInstanceData.prototype, "color", null);
-        __decorate([
-            BABYLON.instanceData()
-        ], Text2DInstanceData.prototype, "superSampleFactor", null);
-        return Text2DInstanceData;
-    }(BABYLON.InstanceDataBase));
-    BABYLON.Text2DInstanceData = Text2DInstanceData;
-    var Text2D = (function (_super) {
-        __extends(Text2D, _super);
-        /**
-         * Create a Text primitive
-         * @param text the text to display
-         * @param settings a combination of settings, possible ones are
-         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
-         * - children: an array of direct children
-         * - id a text identifier, for information purpose
-         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
-         * - rotation: the initial rotation (in radian) of the primitive. default is 0
-         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
-         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
-         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
-         * - zOrder: override the zOrder with the specified value
-         * - origin: define the normalized origin point location, default [0.5;0.5]
-         * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
-         * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
-         * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
-         * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
-         * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
-         * - isVisible: true if the text must be visible, false for hidden. Default is true.
-         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
-         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
-         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
-         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
-         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
-         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
-         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
-         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
-         */
-        function Text2D(text, settings) {
-            if (!settings) {
-                settings = {};
-            }
-            _super.call(this, settings);
-            this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
-            this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
-            this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
-            this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
-            this._textSize = null;
-            this.text = text;
-            this.size = (settings.size == null) ? null : settings.size;
-            this._updateRenderMode();
-        }
-        Object.defineProperty(Text2D.prototype, "fontName", {
-            get: function () {
-                return this._fontName;
-            },
-            set: function (value) {
-                if (this._fontName) {
-                    throw new Error("Font Name change is not supported right now.");
-                }
-                this._fontName = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "defaultFontColor", {
-            get: function () {
-                return this._defaultFontColor;
-            },
-            set: function (value) {
-                this._defaultFontColor = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "text", {
-            get: function () {
-                return this._text;
-            },
-            set: function (value) {
-                this._text = value;
-                this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
-                this._size = null;
-                this._updateCharCount();
-                // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
-                var s = this.textSize;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "size", {
-            get: function () {
-                if (this._size != null) {
-                    return this._size;
-                }
-                return this.textSize;
-            },
-            set: function (value) {
-                this._size = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "actualSize", {
-            /**
-             * Get the actual size of the Text2D primitive
-             */
-            get: function () {
-                if (this._actualSize) {
-                    return this._actualSize;
-                }
-                return this.size;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "textSize", {
-            /**
-             * Get the area that bounds the text associated to the primitive
-             */
-            get: function () {
-                if (!this._textSize) {
-                    if (this.owner) {
-                        var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
-                        if (!newSize.equals(this._textSize)) {
-                            this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
-                            this._positioningDirty();
-                        }
-                        this._textSize = newSize;
-                    }
-                    else {
-                        return Text2D.nullSize;
-                    }
-                }
-                return this._textSize;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Text2D.prototype, "fontTexture", {
-            get: function () {
-                if (this._fontTexture) {
-                    return this._fontTexture;
-                }
-                if (this.fontName == null || this.owner == null || this.owner.scene == null) {
-                    return null;
-                }
-                this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
-                return this._fontTexture;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Dispose the primitive, remove it from its parent
-         */
-        Text2D.prototype.dispose = function () {
-            if (!_super.prototype.dispose.call(this)) {
-                return false;
-            }
-            if (this._fontTexture) {
-                BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
-                this._fontTexture = null;
-            }
-            return true;
-        };
-        Text2D.prototype.updateLevelBoundingInfo = function () {
-            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
-        };
-        Text2D.prototype.levelIntersect = function (intersectInfo) {
-            // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
-            return true;
-        };
-        Text2D.prototype.createModelRenderCache = function (modelKey) {
-            var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
-            return renderCache;
-        };
-        Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
-            var renderCache = modelRenderCache;
-            var engine = this.owner.engine;
-            renderCache.fontTexture = this.fontTexture;
-            renderCache.fontTexture.incCachedFontTextureCounter();
-            var vb = new Float32Array(4);
-            for (var i = 0; i < 4; i++) {
-                vb[i] = i;
-            }
-            renderCache.vb = engine.createVertexBuffer(vb);
-            var ib = new Float32Array(6);
-            ib[0] = 0;
-            ib[1] = 2;
-            ib[2] = 1;
-            ib[3] = 0;
-            ib[4] = 3;
-            ib[5] = 2;
-            renderCache.ib = engine.createIndexBuffer(ib);
-            // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
-            var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
-            if (ei) {
-                renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
-            }
-            ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
-            renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
-            return renderCache;
-        };
-        Text2D.prototype.createInstanceDataParts = function () {
-            return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
-        };
-        // Looks like a hack!? Yes! Because that's what it is!
-        // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
-        // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
-        Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
-            if (!this._charCount) {
-                var curText = this._text;
-                this.text = "A";
-                return curText;
-            }
-        };
-        // if obj contains something, we restore the _text property
-        Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
-            if (obj !== undefined) {
-                this.text = obj;
-            }
-        };
-        Text2D.prototype.refreshInstanceDataPart = function (part) {
-            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
-                return false;
-            }
-            if (part.id === Text2D.TEXT2D_MAINPARTID) {
-                var d = part;
-                var texture = this.fontTexture;
-                var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
-                var ts = texture.getSize();
-                var offset = BABYLON.Vector2.Zero();
-                var lh = this.fontTexture.lineHeight;
-                offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
-                var charxpos = 0;
-                d.dataElementCount = this._charCount;
-                d.curElement = 0;
-                for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
-                    var char = _a[_i];
-                    // Line feed
-                    if (char === "\n") {
-                        offset.x = 0;
-                        offset.y -= texture.lineHeight;
-                    }
-                    // Tabulation ?
-                    if (char === "\t") {
-                        var nextPos = charxpos + this._tabulationSize;
-                        nextPos = nextPos - (nextPos % this._tabulationSize);
-                        offset.x += (nextPos - charxpos) * texture.spaceWidth;
-                        charxpos = nextPos;
-                        continue;
-                    }
-                    if (char < " ") {
-                        continue;
-                    }
-                    this.updateInstanceDataPart(d, offset);
-                    var ci = texture.getChar(char);
-                    offset.x += ci.charWidth;
-                    d.topLeftUV = ci.topLeftUV;
-                    var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
-                    d.sizeUV = suv;
-                    d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
-                    d.color = this.defaultFontColor;
-                    d.superSampleFactor = superSampleFactor;
-                    ++d.curElement;
-                }
-            }
-            return true;
-        };
-        Text2D.prototype._updateCharCount = function () {
-            var count = 0;
-            for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
-                var char = _a[_i];
-                if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
-                    continue;
-                }
-                ++count;
-            }
-            this._charCount = count;
-        };
-        Text2D.prototype._useTextureAlpha = function () {
-            return this.fontTexture != null && this.fontTexture.hasAlpha;
-        };
-        Text2D.prototype._shouldUseAlphaFromTexture = function () {
-            return true;
-        };
-        Text2D.TEXT2D_MAINPARTID = 1;
-        __decorate([
-            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
-        ], Text2D.prototype, "fontName", null);
-        __decorate([
-            BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
-        ], Text2D.prototype, "defaultFontColor", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
-        ], Text2D.prototype, "text", null);
-        __decorate([
-            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
-        ], Text2D.prototype, "size", null);
-        Text2D = __decorate([
-            BABYLON.className("Text2D")
-        ], Text2D);
-        return Text2D;
-    }(BABYLON.RenderablePrim2D));
-    BABYLON.Text2D = Text2D;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.text2d.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+    return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var BABYLON;
+(function (BABYLON) {
+    var Text2DRenderCache = (function (_super) {
+        __extends(Text2DRenderCache, _super);
+        function Text2DRenderCache() {
+            _super.apply(this, arguments);
+            this.effectsReady = false;
+            this.vb = null;
+            this.ib = null;
+            this.instancingAttributes = null;
+            this.fontTexture = null;
+            this.effect = null;
+            this.effectInstanced = null;
+        }
+        Text2DRenderCache.prototype.render = function (instanceInfo, context) {
+            // Do nothing if the shader is still loading/preparing 
+            if (!this.effectsReady) {
+                if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
+                    return false;
+                }
+                this.effectsReady = true;
+            }
+            var canvas = instanceInfo.owner.owner;
+            var engine = canvas.engine;
+            this.fontTexture.update();
+            var effect = context.useInstancing ? this.effectInstanced : this.effect;
+            engine.enableEffect(effect);
+            effect.setTexture("diffuseSampler", this.fontTexture);
+            engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
+            var curAlphaMode = engine.getAlphaMode();
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
+            var pid = context.groupInfoPartData[0];
+            if (context.useInstancing) {
+                if (!this.instancingAttributes) {
+                    this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
+                }
+                var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
+                var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
+                canvas._addDrawCallCount(1, context.renderMode);
+                engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
+                engine.draw(true, 0, 6, count);
+                engine.unbindInstanceAttributes();
+            }
+            else {
+                canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
+                for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
+                    this.setupUniforms(effect, 0, pid._partData, i);
+                    engine.draw(true, 0, 6);
+                }
+            }
+            engine.setAlphaMode(curAlphaMode, true);
+            return true;
+        };
+        Text2DRenderCache.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this.vb) {
+                this._engine._releaseBuffer(this.vb);
+                this.vb = null;
+            }
+            if (this.ib) {
+                this._engine._releaseBuffer(this.ib);
+                this.ib = null;
+            }
+            if (this.fontTexture) {
+                this.fontTexture.decCachedFontTextureCounter();
+                this.fontTexture = null;
+            }
+            this.effect = null;
+            this.effectInstanced = null;
+            return true;
+        };
+        return Text2DRenderCache;
+    })(BABYLON.ModelRenderCache);
+    BABYLON.Text2DRenderCache = Text2DRenderCache;
+    var Text2DInstanceData = (function (_super) {
+        __extends(Text2DInstanceData, _super);
+        function Text2DInstanceData(partId, dataElementCount) {
+            _super.call(this, partId, dataElementCount);
+        }
+        Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2DInstanceData.prototype, "color", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
+            get: function () {
+                return null;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        __decorate([
+            BABYLON.instanceData()
+        ], Text2DInstanceData.prototype, "topLeftUV", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Text2DInstanceData.prototype, "sizeUV", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Text2DInstanceData.prototype, "textureSize", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Text2DInstanceData.prototype, "color", null);
+        __decorate([
+            BABYLON.instanceData()
+        ], Text2DInstanceData.prototype, "superSampleFactor", null);
+        return Text2DInstanceData;
+    })(BABYLON.InstanceDataBase);
+    BABYLON.Text2DInstanceData = Text2DInstanceData;
+    var Text2D = (function (_super) {
+        __extends(Text2D, _super);
+        /**
+         * Create a Text primitive
+         * @param text the text to display
+         * @param settings a combination of settings, possible ones are
+         * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
+         * - children: an array of direct children
+         * - id a text identifier, for information purpose
+         * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
+         * - rotation: the initial rotation (in radian) of the primitive. default is 0
+         * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
+         * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
+         * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
+         * - zOrder: override the zOrder with the specified value
+         * - origin: define the normalized origin point location, default [0.5;0.5]
+         * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
+         * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
+         * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
+         * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
+         * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
+         * - isVisible: true if the text must be visible, false for hidden. Default is true.
+         * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
+         * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
+         * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
+         * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
+         * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
+         * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
+         * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
+         * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
+         */
+        function Text2D(text, settings) {
+            if (!settings) {
+                settings = {};
+            }
+            _super.call(this, settings);
+            this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
+            this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
+            this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
+            this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
+            this._textSize = null;
+            this.text = text;
+            this.size = (settings.size == null) ? null : settings.size;
+            this._updateRenderMode();
+        }
+        Object.defineProperty(Text2D.prototype, "fontName", {
+            get: function () {
+                return this._fontName;
+            },
+            set: function (value) {
+                if (this._fontName) {
+                    throw new Error("Font Name change is not supported right now.");
+                }
+                this._fontName = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "defaultFontColor", {
+            get: function () {
+                return this._defaultFontColor;
+            },
+            set: function (value) {
+                this._defaultFontColor = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "text", {
+            get: function () {
+                return this._text;
+            },
+            set: function (value) {
+                this._text = value;
+                this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
+                this._size = null;
+                this._updateCharCount();
+                // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
+                var s = this.textSize;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "size", {
+            get: function () {
+                if (this._size != null) {
+                    return this._size;
+                }
+                return this.textSize;
+            },
+            set: function (value) {
+                this._size = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "actualSize", {
+            /**
+             * Get the actual size of the Text2D primitive
+             */
+            get: function () {
+                if (this._actualSize) {
+                    return this._actualSize;
+                }
+                return this.size;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "textSize", {
+            /**
+             * Get the area that bounds the text associated to the primitive
+             */
+            get: function () {
+                if (!this._textSize) {
+                    if (this.owner) {
+                        var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
+                        if (!newSize.equals(this._textSize)) {
+                            this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
+                            this._positioningDirty();
+                        }
+                        this._textSize = newSize;
+                    }
+                    else {
+                        return Text2D.nullSize;
+                    }
+                }
+                return this._textSize;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Text2D.prototype, "fontTexture", {
+            get: function () {
+                if (this._fontTexture) {
+                    return this._fontTexture;
+                }
+                if (this.fontName == null || this.owner == null || this.owner.scene == null) {
+                    return null;
+                }
+                this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
+                return this._fontTexture;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Dispose the primitive, remove it from its parent
+         */
+        Text2D.prototype.dispose = function () {
+            if (!_super.prototype.dispose.call(this)) {
+                return false;
+            }
+            if (this._fontTexture) {
+                BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
+                this._fontTexture = null;
+            }
+            return true;
+        };
+        Text2D.prototype.updateLevelBoundingInfo = function () {
+            BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
+        };
+        Text2D.prototype.levelIntersect = function (intersectInfo) {
+            // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
+            return true;
+        };
+        Text2D.prototype.createModelRenderCache = function (modelKey) {
+            var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
+            return renderCache;
+        };
+        Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
+            var renderCache = modelRenderCache;
+            var engine = this.owner.engine;
+            renderCache.fontTexture = this.fontTexture;
+            renderCache.fontTexture.incCachedFontTextureCounter();
+            var vb = new Float32Array(4);
+            for (var i = 0; i < 4; i++) {
+                vb[i] = i;
+            }
+            renderCache.vb = engine.createVertexBuffer(vb);
+            var ib = new Float32Array(6);
+            ib[0] = 0;
+            ib[1] = 2;
+            ib[2] = 1;
+            ib[3] = 0;
+            ib[4] = 3;
+            ib[5] = 2;
+            renderCache.ib = engine.createIndexBuffer(ib);
+            // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
+            var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
+            if (ei) {
+                renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
+            }
+            ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
+            renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
+            return renderCache;
+        };
+        Text2D.prototype.createInstanceDataParts = function () {
+            return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
+        };
+        // Looks like a hack!? Yes! Because that's what it is!
+        // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
+        // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
+        Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
+            if (!this._charCount) {
+                var curText = this._text;
+                this.text = "A";
+                return curText;
+            }
+        };
+        // if obj contains something, we restore the _text property
+        Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
+            if (obj !== undefined) {
+                this.text = obj;
+            }
+        };
+        Text2D.prototype.refreshInstanceDataPart = function (part) {
+            if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
+                return false;
+            }
+            if (part.id === Text2D.TEXT2D_MAINPARTID) {
+                var d = part;
+                var texture = this.fontTexture;
+                var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
+                var ts = texture.getSize();
+                var offset = BABYLON.Vector2.Zero();
+                var lh = this.fontTexture.lineHeight;
+                offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
+                var charxpos = 0;
+                d.dataElementCount = this._charCount;
+                d.curElement = 0;
+                for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
+                    var char = _a[_i];
+                    // Line feed
+                    if (char === "\n") {
+                        offset.x = 0;
+                        offset.y -= texture.lineHeight;
+                    }
+                    // Tabulation ?
+                    if (char === "\t") {
+                        var nextPos = charxpos + this._tabulationSize;
+                        nextPos = nextPos - (nextPos % this._tabulationSize);
+                        offset.x += (nextPos - charxpos) * texture.spaceWidth;
+                        charxpos = nextPos;
+                        continue;
+                    }
+                    if (char < " ") {
+                        continue;
+                    }
+                    this.updateInstanceDataPart(d, offset);
+                    var ci = texture.getChar(char);
+                    offset.x += ci.charWidth;
+                    d.topLeftUV = ci.topLeftUV;
+                    var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
+                    d.sizeUV = suv;
+                    d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
+                    d.color = this.defaultFontColor;
+                    d.superSampleFactor = superSampleFactor;
+                    ++d.curElement;
+                }
+            }
+            return true;
+        };
+        Text2D.prototype._updateCharCount = function () {
+            var count = 0;
+            for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
+                var char = _a[_i];
+                if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
+                    continue;
+                }
+                ++count;
+            }
+            this._charCount = count;
+        };
+        Text2D.prototype._useTextureAlpha = function () {
+            return this.fontTexture != null && this.fontTexture.hasAlpha;
+        };
+        Text2D.prototype._shouldUseAlphaFromTexture = function () {
+            return true;
+        };
+        Text2D.TEXT2D_MAINPARTID = 1;
+        __decorate([
+            BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
+        ], Text2D.prototype, "fontName", null);
+        __decorate([
+            BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
+        ], Text2D.prototype, "defaultFontColor", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
+        ], Text2D.prototype, "text", null);
+        __decorate([
+            BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
+        ], Text2D.prototype, "size", null);
+        Text2D = __decorate([
+            BABYLON.className("Text2D")
+        ], Text2D);
+        return Text2D;
+    })(BABYLON.RenderablePrim2D);
+    BABYLON.Text2D = Text2D;
+})(BABYLON || (BABYLON = {}));

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

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

+ 276 - 277
src/Collisions/babylon.collider.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Plik diff jest za duży
+ 681 - 682
src/Debug/babylon.debugLayer.js


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

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

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

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

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

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

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

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

+ 425 - 426
src/Lights/Shadows/babylon.shadowGenerator.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 212 - 213
src/Materials/Textures/babylon.colorGradingTexture.js

@@ -1,213 +1,212 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
-     * It can help converting any input color in a desired output one. This can then be used to create effects
-     * from sepia, black and white to sixties or futuristic rendering...
-     *
-     * The only supported format is currently 3dl.
-     * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
-     */
-    var ColorGradingTexture = (function (_super) {
-        __extends(ColorGradingTexture, _super);
-        /**
-         * Instantiates a ColorGradingTexture from the following parameters.
-         *
-         * @param url The location of the color gradind data (currently only supporting 3dl)
-         * @param scene The scene the texture will be used in
-         */
-        function ColorGradingTexture(url, scene) {
-            _super.call(this, scene);
-            if (!url) {
-                return;
-            }
-            this._textureMatrix = BABYLON.Matrix.Identity();
-            this.name = url;
-            this.url = url;
-            this.hasAlpha = false;
-            this.isCube = false;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.anisotropicFilteringLevel = 1;
-            this._texture = this._getFromCache(url, true);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this.loadTexture();
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-        }
-        /**
-         * Returns the texture matrix used in most of the material.
-         * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
-         */
-        ColorGradingTexture.prototype.getTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        /**
-         * Occurs when the file being loaded is a .3dl LUT file.
-         */
-        ColorGradingTexture.prototype.load3dlTexture = function () {
-            var _this = this;
-            var mipLevels = 0;
-            var floatArrayView = null;
-            var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
-            this._texture = texture;
-            var callback = function (text) {
-                var data;
-                var tempData;
-                var line;
-                var lines = text.split('\n');
-                var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
-                var maxColor = 0;
-                for (var i = 0; i < lines.length; i++) {
-                    line = lines[i];
-                    if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
-                        continue;
-                    if (line.indexOf('#') === 0)
-                        continue;
-                    var words = line.split(" ");
-                    if (size === 0) {
-                        // Number of space + one
-                        size = words.length;
-                        data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
-                        tempData = new Float32Array(size * size * size * 4);
-                        continue;
-                    }
-                    if (size != 0) {
-                        var r = Math.max(parseInt(words[0]), 0);
-                        var g = Math.max(parseInt(words[1]), 0);
-                        var b = Math.max(parseInt(words[2]), 0);
-                        maxColor = Math.max(r, maxColor);
-                        maxColor = Math.max(g, maxColor);
-                        maxColor = Math.max(b, maxColor);
-                        var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
-                        tempData[pixelStorageIndex + 0] = r;
-                        tempData[pixelStorageIndex + 1] = g;
-                        tempData[pixelStorageIndex + 2] = b;
-                        tempData[pixelStorageIndex + 3] = 0;
-                        pixelIndexSlice++;
-                        if (pixelIndexSlice % size == 0) {
-                            pixelIndexH++;
-                            pixelIndexSlice = 0;
-                            if (pixelIndexH % size == 0) {
-                                pixelIndexW++;
-                                pixelIndexH = 0;
-                            }
-                        }
-                    }
-                }
-                for (var i = 0; i < tempData.length; i++) {
-                    var value = tempData[i];
-                    data[i] = (value / maxColor * 255);
-                }
-                _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
-                _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
-            };
-            BABYLON.Tools.LoadFile(this.url, callback);
-            return this._texture;
-        };
-        /**
-         * Starts the loading process of the texture.
-         */
-        ColorGradingTexture.prototype.loadTexture = function () {
-            if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
-                this.load3dlTexture();
-            }
-        };
-        /**
-         * Clones the color gradind texture.
-         */
-        ColorGradingTexture.prototype.clone = function () {
-            var newTexture = new ColorGradingTexture(this.url, this.getScene());
-            // Base texture
-            newTexture.level = this.level;
-            return newTexture;
-        };
-        /**
-         * Called during delayed load for textures.
-         */
-        ColorGradingTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, true);
-            if (!this._texture) {
-                this.loadTexture();
-            }
-        };
-        /**
-        * Binds the color grading to the shader.
-        * @param colorGrading The texture to bind
-        * @param effect The effect to bind to
-        */
-        ColorGradingTexture.Bind = function (colorGrading, effect) {
-            effect.setTexture("cameraColorGrading2DSampler", colorGrading);
-            var x = colorGrading.level; // Texture Level
-            var y = colorGrading.getSize().height; // Texture Size example with 8
-            var z = y - 1.0; // SizeMinusOne 8 - 1
-            var w = 1 / y; // Space of 1 slice 1 / 8
-            effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
-            var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
-            var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8					    // Space of 1 pixel in V direction, e.g. 1/8
-            var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
-            var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
-            var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64 
-            var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
-            effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
-        };
-        /**
-         * Prepare the list of uniforms associated with the ColorGrading effects.
-         * @param uniformsList The list of uniforms used in the effect
-         * @param samplersList The list of samplers used in the effect
-         */
-        ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
-            uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
-            samplersList.push("cameraColorGrading2DSampler");
-        };
-        /**
-         * Parses a color grading texture serialized by Babylon.
-         * @param parsedTexture The texture information being parsedTexture
-         * @param scene The scene to load the texture in
-         * @param rootUrl The root url of the data assets to load
-         * @return A color gradind texture
-         */
-        ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
-                texture.name = parsedTexture.name;
-                texture.level = parsedTexture.level;
-            }
-            return texture;
-        };
-        /**
-         * Serializes the LUT texture to json format.
-         */
-        ColorGradingTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.level = this.level;
-            serializationObject.customType = "BABYLON.ColorGradingTexture";
-            return serializationObject;
-        };
-        /**
-         * Empty line regex stored for GC.
-         */
-        ColorGradingTexture._noneEmptyLineRegex = /\S+/;
-        return ColorGradingTexture;
-    }(BABYLON.BaseTexture));
-    BABYLON.ColorGradingTexture = ColorGradingTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.colorGradingTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
+     * It can help converting any input color in a desired output one. This can then be used to create effects
+     * from sepia, black and white to sixties or futuristic rendering...
+     *
+     * The only supported format is currently 3dl.
+     * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
+     */
+    var ColorGradingTexture = (function (_super) {
+        __extends(ColorGradingTexture, _super);
+        /**
+         * Instantiates a ColorGradingTexture from the following parameters.
+         *
+         * @param url The location of the color gradind data (currently only supporting 3dl)
+         * @param scene The scene the texture will be used in
+         */
+        function ColorGradingTexture(url, scene) {
+            _super.call(this, scene);
+            if (!url) {
+                return;
+            }
+            this._textureMatrix = BABYLON.Matrix.Identity();
+            this.name = url;
+            this.url = url;
+            this.hasAlpha = false;
+            this.isCube = false;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.anisotropicFilteringLevel = 1;
+            this._texture = this._getFromCache(url, true);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this.loadTexture();
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+        }
+        /**
+         * Returns the texture matrix used in most of the material.
+         * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
+         */
+        ColorGradingTexture.prototype.getTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        /**
+         * Occurs when the file being loaded is a .3dl LUT file.
+         */
+        ColorGradingTexture.prototype.load3dlTexture = function () {
+            var _this = this;
+            var mipLevels = 0;
+            var floatArrayView = null;
+            var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
+            this._texture = texture;
+            var callback = function (text) {
+                var data;
+                var tempData;
+                var line;
+                var lines = text.split('\n');
+                var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
+                var maxColor = 0;
+                for (var i = 0; i < lines.length; i++) {
+                    line = lines[i];
+                    if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
+                        continue;
+                    if (line.indexOf('#') === 0)
+                        continue;
+                    var words = line.split(" ");
+                    if (size === 0) {
+                        // Number of space + one
+                        size = words.length;
+                        data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
+                        tempData = new Float32Array(size * size * size * 4);
+                        continue;
+                    }
+                    if (size != 0) {
+                        var r = Math.max(parseInt(words[0]), 0);
+                        var g = Math.max(parseInt(words[1]), 0);
+                        var b = Math.max(parseInt(words[2]), 0);
+                        maxColor = Math.max(r, maxColor);
+                        maxColor = Math.max(g, maxColor);
+                        maxColor = Math.max(b, maxColor);
+                        var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
+                        tempData[pixelStorageIndex + 0] = r;
+                        tempData[pixelStorageIndex + 1] = g;
+                        tempData[pixelStorageIndex + 2] = b;
+                        tempData[pixelStorageIndex + 3] = 0;
+                        pixelIndexSlice++;
+                        if (pixelIndexSlice % size == 0) {
+                            pixelIndexH++;
+                            pixelIndexSlice = 0;
+                            if (pixelIndexH % size == 0) {
+                                pixelIndexW++;
+                                pixelIndexH = 0;
+                            }
+                        }
+                    }
+                }
+                for (var i = 0; i < tempData.length; i++) {
+                    var value = tempData[i];
+                    data[i] = (value / maxColor * 255);
+                }
+                _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
+                _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
+            };
+            BABYLON.Tools.LoadFile(this.url, callback);
+            return this._texture;
+        };
+        /**
+         * Starts the loading process of the texture.
+         */
+        ColorGradingTexture.prototype.loadTexture = function () {
+            if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
+                this.load3dlTexture();
+            }
+        };
+        /**
+         * Clones the color gradind texture.
+         */
+        ColorGradingTexture.prototype.clone = function () {
+            var newTexture = new ColorGradingTexture(this.url, this.getScene());
+            // Base texture
+            newTexture.level = this.level;
+            return newTexture;
+        };
+        /**
+         * Called during delayed load for textures.
+         */
+        ColorGradingTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, true);
+            if (!this._texture) {
+                this.loadTexture();
+            }
+        };
+        /**
+        * Binds the color grading to the shader.
+        * @param colorGrading The texture to bind
+        * @param effect The effect to bind to
+        */
+        ColorGradingTexture.Bind = function (colorGrading, effect) {
+            effect.setTexture("cameraColorGrading2DSampler", colorGrading);
+            var x = colorGrading.level; // Texture Level
+            var y = colorGrading.getSize().height; // Texture Size example with 8
+            var z = y - 1.0; // SizeMinusOne 8 - 1
+            var w = 1 / y; // Space of 1 slice 1 / 8
+            effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
+            var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
+            var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8					    // Space of 1 pixel in V direction, e.g. 1/8
+            var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
+            var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
+            var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64 
+            var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
+            effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
+        };
+        /**
+         * Prepare the list of uniforms associated with the ColorGrading effects.
+         * @param uniformsList The list of uniforms used in the effect
+         * @param samplersList The list of samplers used in the effect
+         */
+        ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
+            uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
+            samplersList.push("cameraColorGrading2DSampler");
+        };
+        /**
+         * Parses a color grading texture serialized by Babylon.
+         * @param parsedTexture The texture information being parsedTexture
+         * @param scene The scene to load the texture in
+         * @param rootUrl The root url of the data assets to load
+         * @return A color gradind texture
+         */
+        ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
+                texture.name = parsedTexture.name;
+                texture.level = parsedTexture.level;
+            }
+            return texture;
+        };
+        /**
+         * Serializes the LUT texture to json format.
+         */
+        ColorGradingTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.level = this.level;
+            serializationObject.customType = "BABYLON.ColorGradingTexture";
+            return serializationObject;
+        };
+        /**
+         * Empty line regex stored for GC.
+         */
+        ColorGradingTexture._noneEmptyLineRegex = /\S+/;
+        return ColorGradingTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.ColorGradingTexture = ColorGradingTexture;
+})(BABYLON || (BABYLON = {}));

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

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

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

@@ -1,94 +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, 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 = {}));
-//# sourceMappingURL=babylon.dynamicTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var 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, 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 = {}));

+ 313 - 314
src/Materials/Textures/babylon.fontTexture.js

@@ -1,314 +1,313 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * This class given information about a given character.
-     */
-    var CharInfo = (function () {
-        function CharInfo() {
-        }
-        return CharInfo;
-    }());
-    BABYLON.CharInfo = CharInfo;
-    var FontTexture = (function (_super) {
-        __extends(FontTexture, _super);
-        /**
-         * Create a new instance of the FontTexture class
-         * @param name the name of the texture
-         * @param font the font to use, use the W3C CSS notation
-         * @param scene the scene that owns the texture
-         * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
-         * @param samplingMode the texture sampling mode
-         * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
-         */
-        function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
-            if (maxCharCount === void 0) { maxCharCount = 200; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            if (superSample === void 0) { superSample = false; }
-            _super.call(this, null, scene, true, false, samplingMode);
-            this._charInfos = {};
-            this._curCharCount = 0;
-            this._lastUpdateCharCount = -1;
-            this._usedCounter = 1;
-            this.name = name;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._superSample = false;
-            if (superSample) {
-                var sfont = this.getSuperSampleFont(font);
-                if (sfont) {
-                    this._superSample = true;
-                    font = sfont;
-                }
-            }
-            // First canvas creation to determine the size of the texture to create
-            this._canvas = document.createElement("canvas");
-            this._context = this._canvas.getContext("2d");
-            this._context.font = font;
-            this._context.fillStyle = "white";
-            this._cachedFontId = null;
-            var res = this.getFontHeight(font);
-            this._lineHeightSuper = res.height;
-            this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
-            this._offset = res.offset - 1;
-            var maxCharWidth = this._context.measureText("W").width;
-            this._spaceWidthSuper = this._context.measureText(" ").width;
-            this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
-            // This is an approximate size, but should always be able to fit at least the maxCharCount
-            var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
-            var edge = Math.sqrt(totalEstSurface);
-            var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
-            // Create the texture that will store the font characters
-            this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
-            var textureSize = this.getSize();
-            this.hasAlpha = true;
-            // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
-            this._canvas = document.createElement("canvas");
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this._context = this._canvas.getContext("2d");
-            this._context.textBaseline = "top";
-            this._context.font = font;
-            this._context.fillStyle = "white";
-            this._context.imageSmoothingEnabled = false;
-            this._currentFreePosition = BABYLON.Vector2.Zero();
-            // Add the basic ASCII based characters
-            for (var i = 0x20; i < 0x7F; i++) {
-                var c = String.fromCharCode(i);
-                this.getChar(c);
-            }
-            this.update();
-        }
-        Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
-            get: function () {
-                return this._superSample;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FontTexture.prototype, "spaceWidth", {
-            get: function () {
-                return this._spaceWidth;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(FontTexture.prototype, "lineHeight", {
-            get: function () {
-                return this._lineHeight;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
-            if (supersample === void 0) { supersample = false; }
-            var s = scene;
-            if (!s.__fontTextureCache__) {
-                s.__fontTextureCache__ = new BABYLON.StringDictionary();
-            }
-            var dic = s.__fontTextureCache__;
-            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
-            var ft = dic.get(lfn);
-            if (ft) {
-                ++ft._usedCounter;
-                return ft;
-            }
-            ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
-            ft._cachedFontId = lfn;
-            dic.add(lfn, ft);
-            return ft;
-        };
-        FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
-            if (supersample === void 0) { supersample = false; }
-            var s = scene;
-            var dic = s.__fontTextureCache__;
-            if (!dic) {
-                return;
-            }
-            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
-            var font = dic.get(lfn);
-            if (--font._usedCounter === 0) {
-                dic.remove(lfn);
-                font.dispose();
-            }
-        };
-        /**
-         * Make sure the given char is present in the font map.
-         * @param char the character to get or add
-         * @return the CharInfo instance corresponding to the given character
-         */
-        FontTexture.prototype.getChar = function (char) {
-            if (char.length !== 1) {
-                return null;
-            }
-            var info = this._charInfos[char];
-            if (info) {
-                return info;
-            }
-            info = new CharInfo();
-            var measure = this._context.measureText(char);
-            var textureSize = this.getSize();
-            // we reached the end of the current line?
-            var width = Math.round(measure.width);
-            var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
-            var yMargin = xMargin;
-            if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
-                this._currentFreePosition.x = 0;
-                this._currentFreePosition.y += this._lineHeightSuper + yMargin;
-                // No more room?
-                if (this._currentFreePosition.y > textureSize.height) {
-                    return this.getChar("!");
-                }
-            }
-            // Draw the character in the texture
-            this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
-            // Fill the CharInfo object
-            info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
-            info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
-            info.charWidth = this._superSample ? (width / 2) : width;
-            // Add the info structure
-            this._charInfos[char] = info;
-            this._curCharCount++;
-            // Set the next position
-            this._currentFreePosition.x += width + xMargin;
-            return info;
-        };
-        FontTexture.prototype.measureText = function (text, tabulationSize) {
-            if (tabulationSize === void 0) { tabulationSize = 4; }
-            var maxWidth = 0;
-            var curWidth = 0;
-            var lineCount = 1;
-            var charxpos = 0;
-            // Parse each char of the string
-            for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
-                var char = text_1[_i];
-                // Next line feed?
-                if (char === "\n") {
-                    maxWidth = Math.max(maxWidth, curWidth);
-                    charxpos = 0;
-                    curWidth = 0;
-                    ++lineCount;
-                    continue;
-                }
-                // Tabulation ?
-                if (char === "\t") {
-                    var nextPos = charxpos + tabulationSize;
-                    nextPos = nextPos - (nextPos % tabulationSize);
-                    curWidth += (nextPos - charxpos) * this.spaceWidth;
-                    charxpos = nextPos;
-                    continue;
-                }
-                if (char < " ") {
-                    continue;
-                }
-                curWidth += this.getChar(char).charWidth;
-                ++charxpos;
-            }
-            maxWidth = Math.max(maxWidth, curWidth);
-            return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
-        };
-        FontTexture.prototype.getSuperSampleFont = function (font) {
-            // Eternal thank to http://stackoverflow.com/a/10136041/802124
-            var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
-            var res = font.toLocaleLowerCase().match(regex);
-            if (res == null) {
-                return null;
-            }
-            var size = parseInt(res[4]);
-            res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
-            var newFont = "";
-            for (var j = 1; j < res.length; j++) {
-                if (res[j] != null) {
-                    newFont += res[j] + " ";
-                }
-            }
-            return newFont;
-        };
-        // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
-        FontTexture.prototype.getFontHeight = function (font) {
-            var fontDraw = document.createElement("canvas");
-            var ctx = fontDraw.getContext('2d');
-            ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
-            ctx.textBaseline = 'top';
-            ctx.fillStyle = 'white';
-            ctx.font = font;
-            ctx.fillText('jH|', 0, 0);
-            var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
-            var start = -1;
-            var end = -1;
-            for (var row = 0; row < fontDraw.height; row++) {
-                for (var column = 0; column < fontDraw.width; column++) {
-                    var index = (row * fontDraw.width + column) * 4;
-                    if (pixels[index] === 0) {
-                        if (column === fontDraw.width - 1 && start !== -1) {
-                            end = row;
-                            row = fontDraw.height;
-                            break;
-                        }
-                        continue;
-                    }
-                    else {
-                        if (start === -1) {
-                            start = row;
-                        }
-                        break;
-                    }
-                }
-            }
-            return { height: (end - start) + 1, offset: start - 1 };
-        };
-        Object.defineProperty(FontTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        FontTexture.prototype.getContext = function () {
-            return this._context;
-        };
-        /**
-         * Call this method when you've call getChar() at least one time, this will update the texture if needed.
-         * Don't be afraid to call it, if no new character was added, this method simply does nothing.
-         */
-        FontTexture.prototype.update = function () {
-            // Update only if there's new char added since the previous update
-            if (this._lastUpdateCharCount < this._curCharCount) {
-                this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
-                this._lastUpdateCharCount = this._curCharCount;
-            }
-        };
-        // cloning should be prohibited, there's no point to duplicate this texture at all
-        FontTexture.prototype.clone = function () {
-            return null;
-        };
-        /**
-         * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
-         * When the other party is done with this object, decCachedFontTextureCounter must be called.
-         */
-        FontTexture.prototype.incCachedFontTextureCounter = function () {
-            ++this._usedCounter;
-        };
-        /**
-         * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
-         */
-        FontTexture.prototype.decCachedFontTextureCounter = function () {
-            var s = this.getScene();
-            var dic = s.__fontTextureCache__;
-            if (!dic) {
-                return;
-            }
-            if (--this._usedCounter === 0) {
-                dic.remove(this._cachedFontId);
-                this.dispose();
-            }
-        };
-        return FontTexture;
-    }(BABYLON.Texture));
-    BABYLON.FontTexture = FontTexture;
-})(BABYLON || (BABYLON = {}));
-//# sourceMappingURL=babylon.fontTexture.js.map
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * This class given information about a given character.
+     */
+    var CharInfo = (function () {
+        function CharInfo() {
+        }
+        return CharInfo;
+    })();
+    BABYLON.CharInfo = CharInfo;
+    var FontTexture = (function (_super) {
+        __extends(FontTexture, _super);
+        /**
+         * Create a new instance of the FontTexture class
+         * @param name the name of the texture
+         * @param font the font to use, use the W3C CSS notation
+         * @param scene the scene that owns the texture
+         * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
+         * @param samplingMode the texture sampling mode
+         * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
+         */
+        function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
+            if (maxCharCount === void 0) { maxCharCount = 200; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            if (superSample === void 0) { superSample = false; }
+            _super.call(this, null, scene, true, false, samplingMode);
+            this._charInfos = {};
+            this._curCharCount = 0;
+            this._lastUpdateCharCount = -1;
+            this._usedCounter = 1;
+            this.name = name;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._superSample = false;
+            if (superSample) {
+                var sfont = this.getSuperSampleFont(font);
+                if (sfont) {
+                    this._superSample = true;
+                    font = sfont;
+                }
+            }
+            // First canvas creation to determine the size of the texture to create
+            this._canvas = document.createElement("canvas");
+            this._context = this._canvas.getContext("2d");
+            this._context.font = font;
+            this._context.fillStyle = "white";
+            this._cachedFontId = null;
+            var res = this.getFontHeight(font);
+            this._lineHeightSuper = res.height;
+            this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
+            this._offset = res.offset - 1;
+            var maxCharWidth = this._context.measureText("W").width;
+            this._spaceWidthSuper = this._context.measureText(" ").width;
+            this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
+            // This is an approximate size, but should always be able to fit at least the maxCharCount
+            var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
+            var edge = Math.sqrt(totalEstSurface);
+            var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
+            // Create the texture that will store the font characters
+            this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
+            var textureSize = this.getSize();
+            this.hasAlpha = true;
+            // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
+            this._canvas = document.createElement("canvas");
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+            this._context.textBaseline = "top";
+            this._context.font = font;
+            this._context.fillStyle = "white";
+            this._context.imageSmoothingEnabled = false;
+            this._currentFreePosition = BABYLON.Vector2.Zero();
+            // Add the basic ASCII based characters
+            for (var i = 0x20; i < 0x7F; i++) {
+                var c = String.fromCharCode(i);
+                this.getChar(c);
+            }
+            this.update();
+        }
+        Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
+            get: function () {
+                return this._superSample;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FontTexture.prototype, "spaceWidth", {
+            get: function () {
+                return this._spaceWidth;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(FontTexture.prototype, "lineHeight", {
+            get: function () {
+                return this._lineHeight;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
+            if (supersample === void 0) { supersample = false; }
+            var s = scene;
+            if (!s.__fontTextureCache__) {
+                s.__fontTextureCache__ = new BABYLON.StringDictionary();
+            }
+            var dic = s.__fontTextureCache__;
+            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
+            var ft = dic.get(lfn);
+            if (ft) {
+                ++ft._usedCounter;
+                return ft;
+            }
+            ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
+            ft._cachedFontId = lfn;
+            dic.add(lfn, ft);
+            return ft;
+        };
+        FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
+            if (supersample === void 0) { supersample = false; }
+            var s = scene;
+            var dic = s.__fontTextureCache__;
+            if (!dic) {
+                return;
+            }
+            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
+            var font = dic.get(lfn);
+            if (--font._usedCounter === 0) {
+                dic.remove(lfn);
+                font.dispose();
+            }
+        };
+        /**
+         * Make sure the given char is present in the font map.
+         * @param char the character to get or add
+         * @return the CharInfo instance corresponding to the given character
+         */
+        FontTexture.prototype.getChar = function (char) {
+            if (char.length !== 1) {
+                return null;
+            }
+            var info = this._charInfos[char];
+            if (info) {
+                return info;
+            }
+            info = new CharInfo();
+            var measure = this._context.measureText(char);
+            var textureSize = this.getSize();
+            // we reached the end of the current line?
+            var width = Math.round(measure.width);
+            var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
+            var yMargin = xMargin;
+            if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
+                this._currentFreePosition.x = 0;
+                this._currentFreePosition.y += this._lineHeightSuper + yMargin;
+                // No more room?
+                if (this._currentFreePosition.y > textureSize.height) {
+                    return this.getChar("!");
+                }
+            }
+            // Draw the character in the texture
+            this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
+            // Fill the CharInfo object
+            info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
+            info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
+            info.charWidth = this._superSample ? (width / 2) : width;
+            // Add the info structure
+            this._charInfos[char] = info;
+            this._curCharCount++;
+            // Set the next position
+            this._currentFreePosition.x += width + xMargin;
+            return info;
+        };
+        FontTexture.prototype.measureText = function (text, tabulationSize) {
+            if (tabulationSize === void 0) { tabulationSize = 4; }
+            var maxWidth = 0;
+            var curWidth = 0;
+            var lineCount = 1;
+            var charxpos = 0;
+            // Parse each char of the string
+            for (var _i = 0; _i < text.length; _i++) {
+                var char = text[_i];
+                // Next line feed?
+                if (char === "\n") {
+                    maxWidth = Math.max(maxWidth, curWidth);
+                    charxpos = 0;
+                    curWidth = 0;
+                    ++lineCount;
+                    continue;
+                }
+                // Tabulation ?
+                if (char === "\t") {
+                    var nextPos = charxpos + tabulationSize;
+                    nextPos = nextPos - (nextPos % tabulationSize);
+                    curWidth += (nextPos - charxpos) * this.spaceWidth;
+                    charxpos = nextPos;
+                    continue;
+                }
+                if (char < " ") {
+                    continue;
+                }
+                curWidth += this.getChar(char).charWidth;
+                ++charxpos;
+            }
+            maxWidth = Math.max(maxWidth, curWidth);
+            return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
+        };
+        FontTexture.prototype.getSuperSampleFont = function (font) {
+            // Eternal thank to http://stackoverflow.com/a/10136041/802124
+            var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
+            var res = font.toLocaleLowerCase().match(regex);
+            if (res == null) {
+                return null;
+            }
+            var size = parseInt(res[4]);
+            res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
+            var newFont = "";
+            for (var j = 1; j < res.length; j++) {
+                if (res[j] != null) {
+                    newFont += res[j] + " ";
+                }
+            }
+            return newFont;
+        };
+        // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
+        FontTexture.prototype.getFontHeight = function (font) {
+            var fontDraw = document.createElement("canvas");
+            var ctx = fontDraw.getContext('2d');
+            ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
+            ctx.textBaseline = 'top';
+            ctx.fillStyle = 'white';
+            ctx.font = font;
+            ctx.fillText('jH|', 0, 0);
+            var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
+            var start = -1;
+            var end = -1;
+            for (var row = 0; row < fontDraw.height; row++) {
+                for (var column = 0; column < fontDraw.width; column++) {
+                    var index = (row * fontDraw.width + column) * 4;
+                    if (pixels[index] === 0) {
+                        if (column === fontDraw.width - 1 && start !== -1) {
+                            end = row;
+                            row = fontDraw.height;
+                            break;
+                        }
+                        continue;
+                    }
+                    else {
+                        if (start === -1) {
+                            start = row;
+                        }
+                        break;
+                    }
+                }
+            }
+            return { height: (end - start) + 1, offset: start - 1 };
+        };
+        Object.defineProperty(FontTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        FontTexture.prototype.getContext = function () {
+            return this._context;
+        };
+        /**
+         * Call this method when you've call getChar() at least one time, this will update the texture if needed.
+         * Don't be afraid to call it, if no new character was added, this method simply does nothing.
+         */
+        FontTexture.prototype.update = function () {
+            // Update only if there's new char added since the previous update
+            if (this._lastUpdateCharCount < this._curCharCount) {
+                this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
+                this._lastUpdateCharCount = this._curCharCount;
+            }
+        };
+        // cloning should be prohibited, there's no point to duplicate this texture at all
+        FontTexture.prototype.clone = function () {
+            return null;
+        };
+        /**
+         * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
+         * When the other party is done with this object, decCachedFontTextureCounter must be called.
+         */
+        FontTexture.prototype.incCachedFontTextureCounter = function () {
+            ++this._usedCounter;
+        };
+        /**
+         * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
+         */
+        FontTexture.prototype.decCachedFontTextureCounter = function () {
+            var s = this.getScene();
+            var dic = s.__fontTextureCache__;
+            if (!dic) {
+                return;
+            }
+            if (--this._usedCounter === 0) {
+                dic.remove(this._cachedFontId);
+                this.dispose();
+            }
+        };
+        return FontTexture;
+    })(BABYLON.Texture);
+    BABYLON.FontTexture = FontTexture;
+})(BABYLON || (BABYLON = {}));

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

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

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

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

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

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

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

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

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

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

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


Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików