فهرست منبع

Serialization/Parsing refactoring done

David Catuhe 9 سال پیش
والد
کامیت
e34bc65217
45فایلهای تغییر یافته به همراه13923 افزوده شده و 13990 حذف شده
  1. 14 13
      dist/preview release/babylon.core.js
  2. 1005 996
      dist/preview release/babylon.d.ts
  3. 20 20
      dist/preview release/babylon.js
  4. 246 274
      dist/preview release/babylon.max.js
  5. 23 23
      dist/preview release/babylon.noworker.js
  6. 1 1
      src/Actions/babylon.actionManager.js
  7. 460 460
      src/Actions/babylon.actionManager.ts
  8. 1 1
      src/Animations/babylon.animation.js
  9. 601 601
      src/Animations/babylon.animation.ts
  10. 1 1
      src/Audio/babylon.sound.js
  11. 518 518
      src/Audio/babylon.sound.ts
  12. 2 2
      src/Bones/babylon.skeleton.js
  13. 186 186
      src/Bones/babylon.skeleton.ts
  14. 2 2
      src/Cameras/babylon.camera.js
  15. 738 738
      src/Cameras/babylon.camera.ts
  16. 1 1
      src/LensFlare/babylon.lensFlareSystem.js
  17. 271 271
      src/LensFlare/babylon.lensFlareSystem.ts
  18. 1 1
      src/Lights/Shadows/babylon.shadowGenerator.js
  19. 446 446
      src/Lights/Shadows/babylon.shadowGenerator.ts
  20. 2 2
      src/Lights/babylon.light.js
  21. 199 199
      src/Lights/babylon.light.ts
  22. 34 34
      src/Loading/Plugins/babylon.babylonFileLoader.js
  23. 433 433
      src/Loading/Plugins/babylon.babylonFileLoader.ts
  24. 0 60
      src/Materials/Textures/babylon.baseTexture.js
  25. 169 237
      src/Materials/Textures/babylon.baseTexture.ts
  26. 1 1
      src/Materials/Textures/babylon.cubeTexture.js
  27. 100 100
      src/Materials/Textures/babylon.cubeTexture.ts
  28. 3 3
      src/Materials/Textures/babylon.texture.js
  29. 318 318
      src/Materials/Textures/babylon.texture.ts
  30. 16 5
      src/Materials/babylon.material.js
  31. 311 295
      src/Materials/babylon.material.ts
  32. 0 15
      src/Materials/babylon.multiMaterial.js
  33. 67 86
      src/Materials/babylon.multiMaterial.ts
  34. 21 21
      src/Materials/babylon.standardMaterial.js
  35. 1225 1225
      src/Materials/babylon.standardMaterial.ts
  36. 109 8
      src/Mesh/babylon.geometry.js
  37. 1298 1156
      src/Mesh/babylon.geometry.ts
  38. 3 3
      src/Mesh/babylon.mesh.js
  39. 1913 1913
      src/Mesh/babylon.mesh.ts
  40. 39 0
      src/Mesh/babylon.mesh.vertexData.js
  41. 2233 2180
      src/Mesh/babylon.mesh.vertexData.ts
  42. 1 1
      src/Particles/babylon.particleSystem.js
  43. 515 515
      src/Particles/babylon.particleSystem.ts
  44. 8 116
      src/Tools/babylon.sceneSerializer.js
  45. 368 509
      src/Tools/babylon.sceneSerializer.ts

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 14 - 13
dist/preview release/babylon.core.js


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1005 - 996
dist/preview release/babylon.d.ts


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 20 - 20
dist/preview release/babylon.js


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 246 - 274
dist/preview release/babylon.max.js


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 23 - 23
dist/preview release/babylon.noworker.js


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

@@ -281,7 +281,7 @@ var BABYLON;
             var properties = propertyPath.split(".");
             return properties[properties.length - 1];
         };
-        ActionManager.ParseActions = function (parsedActions, object, scene) {
+        ActionManager.Parse = function (parsedActions, object, scene) {
             var actionManager = new BABYLON.ActionManager(scene);
             if (object === null)
                 scene.actionManager = actionManager;

+ 460 - 460
src/Actions/babylon.actionManager.ts

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

+ 1 - 1
src/Animations/babylon.animation.js

@@ -494,7 +494,7 @@ var BABYLON;
             enumerable: true,
             configurable: true
         });
-        Animation.ParseAnimation = function (parsedAnimation) {
+        Animation.Parse = function (parsedAnimation) {
             var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
             var dataType = parsedAnimation.dataType;
             var keys = [];

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 601 - 601
src/Animations/babylon.animation.ts


+ 1 - 1
src/Audio/babylon.sound.js

@@ -439,7 +439,7 @@ var BABYLON;
                 this._updateDirection();
             }
         };
-        Sound.ParseSound = function (parsedSound, scene, rootUrl) {
+        Sound.Parse = function (parsedSound, scene, rootUrl) {
             var soundName = parsedSound.name;
             var soundUrl = rootUrl + soundName;
             var options = {

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 518 - 518
src/Audio/babylon.sound.ts


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

@@ -122,7 +122,7 @@ var BABYLON;
             }
             return serializationObject;
         };
-        Skeleton.ParseSkeleton = function (parsedSkeleton, scene) {
+        Skeleton.Parse = function (parsedSkeleton, scene) {
             var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
             for (var index = 0; index < parsedSkeleton.bones.length; index++) {
                 var parsedBone = parsedSkeleton.bones[index];
@@ -132,7 +132,7 @@ var BABYLON;
                 }
                 var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
                 if (parsedBone.animation) {
-                    bone.animations.push(BABYLON.Animation.ParseAnimation(parsedBone.animation));
+                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
                 }
             }
             return skeleton;

+ 186 - 186
src/Bones/babylon.skeleton.ts

@@ -1,187 +1,187 @@
-module BABYLON {
-    export class Skeleton {
-        public bones = new Array<Bone>();
-
-        private _scene: Scene;
-        private _isDirty = true;
-        private _transformMatrices: Float32Array;
-        private _animatables: IAnimatable[];
-        private _identity = Matrix.Identity();
-
-        private _ranges = new Array<AnimationRange>();
-
-        constructor(public name: string, public id: string, scene: Scene) {
-            this.bones = [];
-
-            this._scene = scene;
-
-            scene.skeletons.push(this);
-
-            this.prepare();
-            //make sure it will recalculate the matrix next time prepare is called.
-            this._isDirty = true;
-        }
-
-        // Members
-        public getTransformMatrices(): Float32Array {
-            return this._transformMatrices;
-        }
-
-        public getScene(): Scene {
-            return this._scene;
-        }
-
-        // Methods
-        public createAnimationRange(name: string, from: number, to: number): void {
-            this._ranges.push(new AnimationRange(name, from, to));
-        }
-
-        public deleteAnimationRange(name: string): void {
-            for (var index = 0; index < this._ranges.length; index++) {
-                if (this._ranges[index].name === name) {
-                    this._ranges.splice(index, 1);
-                    return;
-                }
-            }
-        }
-
-        public getAnimationRange(name: string): AnimationRange {
-            for (var index = 0; index < this._ranges.length; index++) {
-                if (this._ranges[index].name === name) {
-                    return this._ranges[index];
-                }
-            }
-
-            return null;
-        }
-
-        public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void {
-            var range = this.getAnimationRange(name);
-
-            if (!range) {
-                return null;
-            }
-
-            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
-        }
-
-        public _markAsDirty(): void {
-            this._isDirty = true;
-        }
-
-        public prepare(): void {
-            if (!this._isDirty) {
-                return;
-            }
-
-            if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
-                this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
-            }
-
-            for (var index = 0; index < this.bones.length; index++) {
-                var bone = this.bones[index];
-                var parentBone = bone.getParent();
-
-                if (parentBone) {
-                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
-                } else {
-                    bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
-                }
-
-                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);                
-            }
-
-            this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
-
-            this._isDirty = false;
-
-            this._scene._activeBones += this.bones.length;
-        }
-
-        public getAnimatables(): IAnimatable[] {
-            if (!this._animatables || this._animatables.length !== this.bones.length) {
-                this._animatables = [];
-
-                for (var index = 0; index < this.bones.length; index++) {
-                    this._animatables.push(this.bones[index]);
-                }
-            }
-
-            return this._animatables;
-        }
-
-        public clone(name: string, id: string): Skeleton {
-            var result = new Skeleton(name, id || name, this._scene);
-
-            for (var index = 0; index < this.bones.length; index++) {
-                var source = this.bones[index];
-                var parentBone = null;
-
-                if (source.getParent()) {
-                    var parentIndex = this.bones.indexOf(source.getParent());
-                    parentBone = result.bones[parentIndex];
-                }
-
-                var bone = new Bone(source.name, result, parentBone, source.getBaseMatrix());
-                Tools.DeepCopy(source.animations, bone.animations);
-            }
-
-            return result;
-        }
-
-        public dispose() {
-            // Animations
-            this.getScene().stopAnimation(this);
-
-            // Remove from scene
-            this.getScene().removeSkeleton(this);
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-
-            serializationObject.bones = [];
-
-            for (var index = 0; index < this.bones.length; index++) {
-                var bone = this.bones[index];
-
-                var serializedBone: any = {
-                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
-                    name: bone.name,
-                    matrix: bone.getLocalMatrix().toArray()
-                };
-
-                serializationObject.bones.push(serializedBone);
-
-                if (bone.animations && bone.animations.length > 0) {
-                    serializedBone.animation = bone.animations[0].serialize();
-                }
-            }
-            return serializationObject;
-        }
-        
-        public static ParseSkeleton(parsedSkeleton: any, scene: Scene) : Skeleton {
-            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
-
-            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
-                var parsedBone = parsedSkeleton.bones[index];
-    
-                var parentBone = null;
-                if (parsedBone.parentBoneIndex > -1) {
-                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
-                }
-    
-                var bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix));
-    
-                if (parsedBone.animation) {
-                    bone.animations.push(Animation.ParseAnimation(parsedBone.animation));
-                }
-            }
-    
-            return skeleton;
-        }
-    }
+module BABYLON {
+    export class Skeleton {
+        public bones = new Array<Bone>();
+
+        private _scene: Scene;
+        private _isDirty = true;
+        private _transformMatrices: Float32Array;
+        private _animatables: IAnimatable[];
+        private _identity = Matrix.Identity();
+
+        private _ranges = new Array<AnimationRange>();
+
+        constructor(public name: string, public id: string, scene: Scene) {
+            this.bones = [];
+
+            this._scene = scene;
+
+            scene.skeletons.push(this);
+
+            this.prepare();
+            //make sure it will recalculate the matrix next time prepare is called.
+            this._isDirty = true;
+        }
+
+        // Members
+        public getTransformMatrices(): Float32Array {
+            return this._transformMatrices;
+        }
+
+        public getScene(): Scene {
+            return this._scene;
+        }
+
+        // Methods
+        public createAnimationRange(name: string, from: number, to: number): void {
+            this._ranges.push(new AnimationRange(name, from, to));
+        }
+
+        public deleteAnimationRange(name: string): void {
+            for (var index = 0; index < this._ranges.length; index++) {
+                if (this._ranges[index].name === name) {
+                    this._ranges.splice(index, 1);
+                    return;
+                }
+            }
+        }
+
+        public getAnimationRange(name: string): AnimationRange {
+            for (var index = 0; index < this._ranges.length; index++) {
+                if (this._ranges[index].name === name) {
+                    return this._ranges[index];
+                }
+            }
+
+            return null;
+        }
+
+        public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void {
+            var range = this.getAnimationRange(name);
+
+            if (!range) {
+                return null;
+            }
+
+            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
+        }
+
+        public _markAsDirty(): void {
+            this._isDirty = true;
+        }
+
+        public prepare(): void {
+            if (!this._isDirty) {
+                return;
+            }
+
+            if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
+                this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
+            }
+
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var parentBone = bone.getParent();
+
+                if (parentBone) {
+                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
+                } else {
+                    bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
+                }
+
+                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);                
+            }
+
+            this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
+
+            this._isDirty = false;
+
+            this._scene._activeBones += this.bones.length;
+        }
+
+        public getAnimatables(): IAnimatable[] {
+            if (!this._animatables || this._animatables.length !== this.bones.length) {
+                this._animatables = [];
+
+                for (var index = 0; index < this.bones.length; index++) {
+                    this._animatables.push(this.bones[index]);
+                }
+            }
+
+            return this._animatables;
+        }
+
+        public clone(name: string, id: string): Skeleton {
+            var result = new Skeleton(name, id || name, this._scene);
+
+            for (var index = 0; index < this.bones.length; index++) {
+                var source = this.bones[index];
+                var parentBone = null;
+
+                if (source.getParent()) {
+                    var parentIndex = this.bones.indexOf(source.getParent());
+                    parentBone = result.bones[parentIndex];
+                }
+
+                var bone = new Bone(source.name, result, parentBone, source.getBaseMatrix());
+                Tools.DeepCopy(source.animations, bone.animations);
+            }
+
+            return result;
+        }
+
+        public dispose() {
+            // Animations
+            this.getScene().stopAnimation(this);
+
+            // Remove from scene
+            this.getScene().removeSkeleton(this);
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+
+            serializationObject.bones = [];
+
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+
+                var serializedBone: any = {
+                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
+                    name: bone.name,
+                    matrix: bone.getLocalMatrix().toArray()
+                };
+
+                serializationObject.bones.push(serializedBone);
+
+                if (bone.animations && bone.animations.length > 0) {
+                    serializedBone.animation = bone.animations[0].serialize();
+                }
+            }
+            return serializationObject;
+        }
+        
+        public static Parse(parsedSkeleton: any, scene: Scene) : Skeleton {
+            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
+
+            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
+                var parsedBone = parsedSkeleton.bones[index];
+    
+                var parentBone = null;
+                if (parsedBone.parentBoneIndex > -1) {
+                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
+                }
+    
+                var bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix));
+    
+                if (parsedBone.animation) {
+                    bone.animations.push(Animation.Parse(parsedBone.animation));
+                }
+            }
+    
+            return skeleton;
+        }
+    }
 }

+ 2 - 2
src/Cameras/babylon.camera.js

@@ -537,7 +537,7 @@ var BABYLON;
             serializationObject.layerMask = this.layerMask;
             return serializationObject;
         };
-        Camera.ParseCamera = function (parsedCamera, scene) {
+        Camera.Parse = function (parsedCamera, scene) {
             var camera;
             var position = BABYLON.Vector3.FromArray(parsedCamera.position);
             var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
@@ -630,7 +630,7 @@ var BABYLON;
             if (parsedCamera.animations) {
                 for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
                     var parsedAnimation = parsedCamera.animations[animationIndex];
-                    camera.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
+                    camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                 }
             }
             if (parsedCamera.autoAnimate) {

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 738 - 738
src/Cameras/babylon.camera.ts


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

@@ -176,7 +176,7 @@ var BABYLON;
             var index = this._scene.lensFlareSystems.indexOf(this);
             this._scene.lensFlareSystems.splice(index, 1);
         };
-        LensFlareSystem.ParseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
+        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
             var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
             var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
             lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;

+ 271 - 271
src/LensFlare/babylon.lensFlareSystem.ts

@@ -1,272 +1,272 @@
-module BABYLON {
-    export class LensFlareSystem {
-        public lensFlares = new Array<LensFlare>();
-        public borderLimit = 300;
-        public meshesSelectionPredicate: (mesh: Mesh) => boolean;
-        public layerMask: number = 0x0FFFFFFF;
-
-        private _scene: Scene;
-        private _emitter: any;
-        private _vertexDeclaration = [2];
-        private _vertexStrideSize = 2 * 4;
-        private _vertexBuffer: WebGLBuffer;
-        private _indexBuffer: WebGLBuffer;
-        private _effect: Effect;
-        private _positionX: number;
-        private _positionY: number;
-        private _isEnabled = true;
-
-        constructor(public name: string, emitter: any, scene: Scene) {
-
-            this._scene = scene;
-            this._emitter = emitter;
-            scene.lensFlareSystems.push(this);
-
-            this.meshesSelectionPredicate = m => m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
-
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-
-            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-
-            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-
-            // Effects
-            this._effect = this._scene.getEngine().createEffect("lensFlare",
-                ["position"],
-                ["color", "viewportMatrix"],
-                ["textureSampler"], "");
-        }
-
-        public get isEnabled(): boolean {
-            return this._isEnabled;
-        }
-
-        public set isEnabled(value: boolean) {
-            this._isEnabled = value;
-        }
-
-        public getScene(): Scene {
-            return this._scene;
-        }
-
-        public getEmitter(): any {
-            return this._emitter;
-        }
-
-        public setEmitter(newEmitter: any): void {
-            this._emitter = newEmitter;
-        }
-
-        public getEmitterPosition(): Vector3 {
-            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
-        }
-
-        public computeEffectivePosition(globalViewport: Viewport): boolean {
-            var position = this.getEmitterPosition();
-
-            position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
-
-            this._positionX = position.x;
-            this._positionY = position.y;
-
-            position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
-
-            if (position.z > 0) {
-                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
-                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
-                        return true;
-                }
-            }
-
-            return false;
-        }
-
-        public _isVisible(): boolean {
-            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 Ray(this._scene.activeCamera.position, direction);
-            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
-
-            return !pickInfo.hit || pickInfo.distance > distance;
-        }
-
-        public render(): boolean {
-            if (!this._effect.isReady())
-                return false;
-
-            var engine = this._scene.getEngine();
-            var viewport = this._scene.activeCamera.viewport;
-            var globalViewport = viewport.toGlobal(engine);
-
-            // Position
-            if (!this.computeEffectivePosition(globalViewport)) {
-                return false;
-            }
-
-            // Visibility
-            if (!this._isVisible()) {
-                return false;
-            }
-
-            // Intensity
-            var awayX;
-            var awayY;
-
-            if (this._positionX < this.borderLimit + globalViewport.x) {
-                awayX = this.borderLimit + globalViewport.x - this._positionX;
-            } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
-                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
-            } else {
-                awayX = 0;
-            }
-
-            if (this._positionY < this.borderLimit + globalViewport.y) {
-                awayY = this.borderLimit + globalViewport.y - this._positionY;
-            } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
-                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
-            } else {
-                awayY = 0;
-            }
-
-            var away = (awayX > awayY) ? awayX : awayY;
-            if (away > this.borderLimit) {
-                away = this.borderLimit;
-            }
-
-            var intensity = 1.0 - (away / this.borderLimit);
-            if (intensity < 0) {
-                return false;
-            }
-
-            if (intensity > 1.0) {
-                intensity = 1.0;
-            }
-
-            // Position
-            var centerX = globalViewport.x + globalViewport.width / 2;
-            var centerY = globalViewport.y + globalViewport.height / 2;
-            var distX = centerX - this._positionX;
-            var distY = centerY - this._positionY;
-
-            // Effects
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            engine.setDepthBuffer(false);
-            engine.setAlphaMode(Engine.ALPHA_ONEONE);
-
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
-
-            // Flares
-            for (var index = 0; index < this.lensFlares.length; index++) {
-                var flare = this.lensFlares[index];
-
-                var x = centerX - (distX * flare.position);
-                var y = centerY - (distY * flare.position);
-
-                var cw = flare.size;
-                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
-                var cx = 2 * (x / globalViewport.width) - 1.0;
-                var cy = 1.0 - 2 * (y / globalViewport.height);
-
-                var viewportMatrix = 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(Engine.ALPHA_DISABLE);
-            return true;
-        }
-
-        public dispose(): void {
-            if (this._vertexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-                this._vertexBuffer = null;
-            }
-
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-
-            while (this.lensFlares.length) {
-                this.lensFlares[0].dispose();
-            }
-
-            // Remove from scene
-            var index = this._scene.lensFlareSystems.indexOf(this);
-            this._scene.lensFlareSystems.splice(index, 1);
-        }
-        
-        public static ParseLensFlareSystem(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem {
-            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
-
-            var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
-            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
-
-            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
-                var parsedFlare = parsedLensFlareSystem.flares[index];
-                var flare = new LensFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
-            }
-
-            return lensFlareSystem;
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            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: Tools.GetFilename(flare.texture.name)
-                });
-            }
-
-            return serializationObject;
-        }
-    }
+module BABYLON {
+    export class LensFlareSystem {
+        public lensFlares = new Array<LensFlare>();
+        public borderLimit = 300;
+        public meshesSelectionPredicate: (mesh: Mesh) => boolean;
+        public layerMask: number = 0x0FFFFFFF;
+
+        private _scene: Scene;
+        private _emitter: any;
+        private _vertexDeclaration = [2];
+        private _vertexStrideSize = 2 * 4;
+        private _vertexBuffer: WebGLBuffer;
+        private _indexBuffer: WebGLBuffer;
+        private _effect: Effect;
+        private _positionX: number;
+        private _positionY: number;
+        private _isEnabled = true;
+
+        constructor(public name: string, emitter: any, scene: Scene) {
+
+            this._scene = scene;
+            this._emitter = emitter;
+            scene.lensFlareSystems.push(this);
+
+            this.meshesSelectionPredicate = m => m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
+
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("lensFlare",
+                ["position"],
+                ["color", "viewportMatrix"],
+                ["textureSampler"], "");
+        }
+
+        public get isEnabled(): boolean {
+            return this._isEnabled;
+        }
+
+        public set isEnabled(value: boolean) {
+            this._isEnabled = value;
+        }
+
+        public getScene(): Scene {
+            return this._scene;
+        }
+
+        public getEmitter(): any {
+            return this._emitter;
+        }
+
+        public setEmitter(newEmitter: any): void {
+            this._emitter = newEmitter;
+        }
+
+        public getEmitterPosition(): Vector3 {
+            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
+        }
+
+        public computeEffectivePosition(globalViewport: Viewport): boolean {
+            var position = this.getEmitterPosition();
+
+            position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
+
+            this._positionX = position.x;
+            this._positionY = position.y;
+
+            position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
+
+            if (position.z > 0) {
+                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
+                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
+                        return true;
+                }
+            }
+
+            return false;
+        }
+
+        public _isVisible(): boolean {
+            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 Ray(this._scene.activeCamera.position, direction);
+            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
+
+            return !pickInfo.hit || pickInfo.distance > distance;
+        }
+
+        public render(): boolean {
+            if (!this._effect.isReady())
+                return false;
+
+            var engine = this._scene.getEngine();
+            var viewport = this._scene.activeCamera.viewport;
+            var globalViewport = viewport.toGlobal(engine);
+
+            // Position
+            if (!this.computeEffectivePosition(globalViewport)) {
+                return false;
+            }
+
+            // Visibility
+            if (!this._isVisible()) {
+                return false;
+            }
+
+            // Intensity
+            var awayX;
+            var awayY;
+
+            if (this._positionX < this.borderLimit + globalViewport.x) {
+                awayX = this.borderLimit + globalViewport.x - this._positionX;
+            } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
+                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
+            } else {
+                awayX = 0;
+            }
+
+            if (this._positionY < this.borderLimit + globalViewport.y) {
+                awayY = this.borderLimit + globalViewport.y - this._positionY;
+            } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
+                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
+            } else {
+                awayY = 0;
+            }
+
+            var away = (awayX > awayY) ? awayX : awayY;
+            if (away > this.borderLimit) {
+                away = this.borderLimit;
+            }
+
+            var intensity = 1.0 - (away / this.borderLimit);
+            if (intensity < 0) {
+                return false;
+            }
+
+            if (intensity > 1.0) {
+                intensity = 1.0;
+            }
+
+            // Position
+            var centerX = globalViewport.x + globalViewport.width / 2;
+            var centerY = globalViewport.y + globalViewport.height / 2;
+            var distX = centerX - this._positionX;
+            var distY = centerY - this._positionY;
+
+            // Effects
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            engine.setDepthBuffer(false);
+            engine.setAlphaMode(Engine.ALPHA_ONEONE);
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+
+            // Flares
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
+
+                var x = centerX - (distX * flare.position);
+                var y = centerY - (distY * flare.position);
+
+                var cw = flare.size;
+                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
+                var cx = 2 * (x / globalViewport.width) - 1.0;
+                var cy = 1.0 - 2 * (y / globalViewport.height);
+
+                var viewportMatrix = 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(Engine.ALPHA_DISABLE);
+            return true;
+        }
+
+        public dispose(): void {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+
+            while (this.lensFlares.length) {
+                this.lensFlares[0].dispose();
+            }
+
+            // Remove from scene
+            var index = this._scene.lensFlareSystems.indexOf(this);
+            this._scene.lensFlareSystems.splice(index, 1);
+        }
+        
+        public static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem {
+            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
+
+            var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
+            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
+
+            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
+                var parsedFlare = parsedLensFlareSystem.flares[index];
+                var flare = new LensFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
+            }
+
+            return lensFlareSystem;
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            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: Tools.GetFilename(flare.texture.name)
+                });
+            }
+
+            return serializationObject;
+        }
+    }
 } 

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

@@ -351,7 +351,7 @@ var BABYLON;
             }
             return serializationObject;
         };
-        ShadowGenerator.ParseShadowGenerator = function (parsedShadowGenerator, scene) {
+        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);

+ 446 - 446
src/Lights/Shadows/babylon.shadowGenerator.ts

@@ -1,447 +1,447 @@
-module BABYLON {
-    export class ShadowGenerator {
-        private static _FILTER_NONE = 0;
-        private static _FILTER_VARIANCESHADOWMAP = 1;
-        private static _FILTER_POISSONSAMPLING = 2;
-        private static _FILTER_BLURVARIANCESHADOWMAP = 3;
-
-        // Static
-        public static get FILTER_NONE(): number {
-            return ShadowGenerator._FILTER_NONE;
-        }
-
-        public static get FILTER_VARIANCESHADOWMAP(): number {
-            return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
-        }
-
-        public static get FILTER_POISSONSAMPLING(): number {
-            return ShadowGenerator._FILTER_POISSONSAMPLING;
-        }
-
-        public static get FILTER_BLURVARIANCESHADOWMAP(): number {
-            return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
-        }
-
-        // Members
-        private _filter = ShadowGenerator.FILTER_NONE;
-        public blurScale = 2;
-        private _blurBoxOffset = 0;
-        private _bias = 0.00005;
-        private _lightDirection = Vector3.Zero();
-
-        public get bias(): number {
-            return this._bias;
-        }
-
-        public set bias(bias: number) {
-            this._bias = bias;
-        }
-        public get blurBoxOffset(): number {
-            return this._blurBoxOffset;
-        }
-
-        public set blurBoxOffset(value: number) {
-            if (this._blurBoxOffset === value) {
-                return;
-            }
-
-            this._blurBoxOffset = value;
-
-            if (this._boxBlurPostprocess) {
-                this._boxBlurPostprocess.dispose();
-            }
-
-            this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
-            this._boxBlurPostprocess.onApply = effect => {
-                effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
-            };
-        }
-
-        public get filter(): number {
-            return this._filter;
-        }
-
-        public set filter(value: number) {
-            if (this._filter === value) {
-                return;
-            }
-
-            this._filter = value;
-
-            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
-                this._shadowMap.anisotropicFilteringLevel = 16;
-                this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
-            } else {
-                this._shadowMap.anisotropicFilteringLevel = 1;
-                this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
-            }
-        }
-
-        public get useVarianceShadowMap(): boolean {
-            return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
-        }
-        public set useVarianceShadowMap(value: boolean) {
-            this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-        }
-
-        public get usePoissonSampling(): boolean {
-            return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
-                (!this._light.supportsVSM() && (
-                    this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
-                    this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
-                ));
-        }
-        public set usePoissonSampling(value: boolean) {
-            this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
-        }
-
-        public get useBlurVarianceShadowMap(): boolean {
-            return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
-        }
-        public set useBlurVarianceShadowMap(value: boolean) {
-            this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-        }
-
-        private _light: IShadowLight;
-        private _scene: Scene;
-        private _shadowMap: RenderTargetTexture;
-        private _shadowMap2: RenderTargetTexture;
-        private _darkness = 0;
-        private _transparencyShadow = false;
-        private _effect: Effect;
-
-        private _viewMatrix = Matrix.Zero();
-        private _projectionMatrix = Matrix.Zero();
-        private _transformMatrix = Matrix.Zero();
-        private _worldViewProjection = Matrix.Zero();
-        private _cachedPosition: Vector3;
-        private _cachedDirection: Vector3;
-        private _cachedDefines: string;
-        private _currentRenderID: number;
-        private _downSamplePostprocess: PassPostProcess;
-        private _boxBlurPostprocess: PostProcess;
-        private _mapSize: number;
-        private _currentFaceIndex = 0;
-        private _currentFaceIndexCache = 0;
-
-        constructor(mapSize: number, light: IShadowLight) {
-            this._light = light;
-            this._scene = light.getScene();
-            this._mapSize = mapSize;
-
-            light._shadowGenerator = this;
-
-            // Render target
-            this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
-            this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.anisotropicFilteringLevel = 1;
-            this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
-            this._shadowMap.renderParticles = false;
-
-
-            this._shadowMap.onBeforeRender = (faceIndex: number) => {
-                this._currentFaceIndex = faceIndex;
-            }
-
-            this._shadowMap.onAfterUnbind = () => {
-                if (!this.useBlurVarianceShadowMap) {
-                    return;
-                }
-
-                if (!this._shadowMap2) {
-                    this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
-                    this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
-                    this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
-                    this._shadowMap2.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
-
-                    this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
-                    this._downSamplePostprocess.onApply = 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 = (subMesh: SubMesh): void => {
-                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);
-
-                if (this.isReady(subMesh, hardwareInstancedRendering)) {
-                    engine.enableEffect(this._effect);
-                    mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
-                    var material = subMesh.getMaterial();
-
-                    this._effect.setMatrix("viewProjection", this.getTransformMatrix());
-
-                    // 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());
-                    }
-
-                    // Draw
-                    mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
-                        (isInstance, world) => this._effect.setMatrix("world", world));
-                } else {
-                    // Need to reset refresh rate of the shadowMap
-                    this._shadowMap.resetRefreshCounter();
-                }
-            };
-
-            this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
-                var index: number;
-
-                for (index = 0; index < opaqueSubMeshes.length; index++) {
-                    renderSubMesh(opaqueSubMeshes.data[index]);
-                }
-
-                for (index = 0; index < alphaTestSubMeshes.length; index++) {
-                    renderSubMesh(alphaTestSubMeshes.data[index]);
-                }
-
-                if (this._transparencyShadow) {
-                    for (index = 0; index < transparentSubMeshes.length; index++) {
-                        renderSubMesh(transparentSubMeshes.data[index]);
-                    }
-                }
-            };
-
-            this._shadowMap.onClear = (engine: Engine) => {
-                if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
-                    engine.clear(new Color4(0, 0, 0, 0), true, true);
-                } else {
-                    engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
-                }
-            }
-        }
-
-        public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
-            var defines = [];
-
-            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
-                defines.push("#define VSM");
-            }
-
-            var attribs = [VertexBuffer.PositionKind];
-
-            var mesh = subMesh.getMesh();
-            var material = subMesh.getMaterial();
-
-            // Alpha test
-            if (material && material.needAlphaTesting()) {
-                defines.push("#define ALPHATEST");
-                if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
-                    attribs.push(VertexBuffer.UVKind);
-                    defines.push("#define UV1");
-                }
-                if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
-                    attribs.push(VertexBuffer.UV2Kind);
-                    defines.push("#define UV2");
-                }
-            }
-
-            // Bones
-            if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                attribs.push(VertexBuffer.MatricesIndicesKind);
-                attribs.push(VertexBuffer.MatricesWeightsKind);
-                if (mesh.numBoneInfluencers > 4) {
-                    attribs.push(VertexBuffer.MatricesIndicesExtraKind);
-                    attribs.push(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"],
-                    ["diffuseSampler"], join);
-            }
-
-            return this._effect.isReady();
-        }
-
-        public getShadowMap(): RenderTargetTexture {
-            return this._shadowMap;
-        }
-
-        public getShadowMapForRendering(): RenderTargetTexture {
-            if (this._shadowMap2) {
-                return this._shadowMap2;
-            }
-
-            return this._shadowMap;
-        }
-
-        public getLight(): IShadowLight {
-            return this._light;
-        }
-
-        // Methods
-        public getTransformMatrix(): Matrix {
-            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;
-            Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
-
-            if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
-                this._lightDirection.z = 0.0000000000001; // Need 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();
-
-                Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
-
-                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
-
-                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
-            }
-
-            return this._transformMatrix;
-        }
-
-        public getDarkness(): number {
-            return this._darkness;
-        }
-
-        public setDarkness(darkness: number): void {
-            if (darkness >= 1.0)
-                this._darkness = 1.0;
-            else if (darkness <= 0.0)
-                this._darkness = 0.0;
-            else
-                this._darkness = darkness;
-        }
-
-        public setTransparencyShadow(hasShadow: boolean): void {
-            this._transparencyShadow = hasShadow;
-        }
-
-        private _packHalf(depth: number): Vector2 {
-            var scale = depth * 255.0;
-            var fract = scale - Math.floor(scale);
-
-            return new Vector2(depth - fract / 255.0, fract);
-        }
-
-        public dispose(): void {
-            this._shadowMap.dispose();
-
-            if (this._shadowMap2) {
-                this._shadowMap2.dispose();
-            }
-
-            if (this._downSamplePostprocess) {
-                this._downSamplePostprocess.dispose();
-            }
-
-            if (this._boxBlurPostprocess) {
-                this._boxBlurPostprocess.dispose();
-            }
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            serializationObject.lightId = this._light.id;
-            serializationObject.mapSize = this.getShadowMap().getRenderSize();
-            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
-            serializationObject.usePoissonSampling = this.usePoissonSampling;
-
-            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;
-        }
-
-        public static ParseShadowGenerator(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
-            //casting to point light, as light is missing the position attr and typescript complains.
-            var light = <PointLight>scene.getLightByID(parsedShadowGenerator.lightId);
-            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
-
-            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
-                var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
-
-                shadowGenerator.getShadowMap().renderList.push(mesh);
-            }
-
-            if (parsedShadowGenerator.usePoissonSampling) {
-                shadowGenerator.usePoissonSampling = true;
-            } else if (parsedShadowGenerator.useVarianceShadowMap) {
-                shadowGenerator.useVarianceShadowMap = true;
-            } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
-                shadowGenerator.useBlurVarianceShadowMap = true;
-
-                if (parsedShadowGenerator.blurScale) {
-                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
-                }
-
-                if (parsedShadowGenerator.blurBoxOffset) {
-                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
-                }
-            }
-
-            if (parsedShadowGenerator.bias !== undefined) {
-                shadowGenerator.bias = parsedShadowGenerator.bias;
-            }
-
-            return shadowGenerator;
-        }
-    }
+module BABYLON {
+    export class ShadowGenerator {
+        private static _FILTER_NONE = 0;
+        private static _FILTER_VARIANCESHADOWMAP = 1;
+        private static _FILTER_POISSONSAMPLING = 2;
+        private static _FILTER_BLURVARIANCESHADOWMAP = 3;
+
+        // Static
+        public static get FILTER_NONE(): number {
+            return ShadowGenerator._FILTER_NONE;
+        }
+
+        public static get FILTER_VARIANCESHADOWMAP(): number {
+            return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
+        }
+
+        public static get FILTER_POISSONSAMPLING(): number {
+            return ShadowGenerator._FILTER_POISSONSAMPLING;
+        }
+
+        public static get FILTER_BLURVARIANCESHADOWMAP(): number {
+            return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
+        }
+
+        // Members
+        private _filter = ShadowGenerator.FILTER_NONE;
+        public blurScale = 2;
+        private _blurBoxOffset = 0;
+        private _bias = 0.00005;
+        private _lightDirection = Vector3.Zero();
+
+        public get bias(): number {
+            return this._bias;
+        }
+
+        public set bias(bias: number) {
+            this._bias = bias;
+        }
+        public get blurBoxOffset(): number {
+            return this._blurBoxOffset;
+        }
+
+        public set blurBoxOffset(value: number) {
+            if (this._blurBoxOffset === value) {
+                return;
+            }
+
+            this._blurBoxOffset = value;
+
+            if (this._boxBlurPostprocess) {
+                this._boxBlurPostprocess.dispose();
+            }
+
+            this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
+            this._boxBlurPostprocess.onApply = effect => {
+                effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
+            };
+        }
+
+        public get filter(): number {
+            return this._filter;
+        }
+
+        public set filter(value: number) {
+            if (this._filter === value) {
+                return;
+            }
+
+            this._filter = value;
+
+            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
+                this._shadowMap.anisotropicFilteringLevel = 16;
+                this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
+            } else {
+                this._shadowMap.anisotropicFilteringLevel = 1;
+                this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
+            }
+        }
+
+        public get useVarianceShadowMap(): boolean {
+            return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
+        }
+        public set useVarianceShadowMap(value: boolean) {
+            this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+        }
+
+        public get usePoissonSampling(): boolean {
+            return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
+                (!this._light.supportsVSM() && (
+                    this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
+                    this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
+                ));
+        }
+        public set usePoissonSampling(value: boolean) {
+            this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
+        }
+
+        public get useBlurVarianceShadowMap(): boolean {
+            return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
+        }
+        public set useBlurVarianceShadowMap(value: boolean) {
+            this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+        }
+
+        private _light: IShadowLight;
+        private _scene: Scene;
+        private _shadowMap: RenderTargetTexture;
+        private _shadowMap2: RenderTargetTexture;
+        private _darkness = 0;
+        private _transparencyShadow = false;
+        private _effect: Effect;
+
+        private _viewMatrix = Matrix.Zero();
+        private _projectionMatrix = Matrix.Zero();
+        private _transformMatrix = Matrix.Zero();
+        private _worldViewProjection = Matrix.Zero();
+        private _cachedPosition: Vector3;
+        private _cachedDirection: Vector3;
+        private _cachedDefines: string;
+        private _currentRenderID: number;
+        private _downSamplePostprocess: PassPostProcess;
+        private _boxBlurPostprocess: PostProcess;
+        private _mapSize: number;
+        private _currentFaceIndex = 0;
+        private _currentFaceIndexCache = 0;
+
+        constructor(mapSize: number, light: IShadowLight) {
+            this._light = light;
+            this._scene = light.getScene();
+            this._mapSize = mapSize;
+
+            light._shadowGenerator = this;
+
+            // Render target
+            this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
+            this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.anisotropicFilteringLevel = 1;
+            this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
+            this._shadowMap.renderParticles = false;
+
+
+            this._shadowMap.onBeforeRender = (faceIndex: number) => {
+                this._currentFaceIndex = faceIndex;
+            }
+
+            this._shadowMap.onAfterUnbind = () => {
+                if (!this.useBlurVarianceShadowMap) {
+                    return;
+                }
+
+                if (!this._shadowMap2) {
+                    this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
+                    this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
+                    this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
+                    this._shadowMap2.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
+
+                    this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
+                    this._downSamplePostprocess.onApply = 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 = (subMesh: SubMesh): void => {
+                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);
+
+                if (this.isReady(subMesh, hardwareInstancedRendering)) {
+                    engine.enableEffect(this._effect);
+                    mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
+                    var material = subMesh.getMaterial();
+
+                    this._effect.setMatrix("viewProjection", this.getTransformMatrix());
+
+                    // 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());
+                    }
+
+                    // Draw
+                    mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
+                        (isInstance, world) => this._effect.setMatrix("world", world));
+                } else {
+                    // Need to reset refresh rate of the shadowMap
+                    this._shadowMap.resetRefreshCounter();
+                }
+            };
+
+            this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
+                var index: number;
+
+                for (index = 0; index < opaqueSubMeshes.length; index++) {
+                    renderSubMesh(opaqueSubMeshes.data[index]);
+                }
+
+                for (index = 0; index < alphaTestSubMeshes.length; index++) {
+                    renderSubMesh(alphaTestSubMeshes.data[index]);
+                }
+
+                if (this._transparencyShadow) {
+                    for (index = 0; index < transparentSubMeshes.length; index++) {
+                        renderSubMesh(transparentSubMeshes.data[index]);
+                    }
+                }
+            };
+
+            this._shadowMap.onClear = (engine: Engine) => {
+                if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
+                    engine.clear(new Color4(0, 0, 0, 0), true, true);
+                } else {
+                    engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
+                }
+            }
+        }
+
+        public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
+            var defines = [];
+
+            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
+                defines.push("#define VSM");
+            }
+
+            var attribs = [VertexBuffer.PositionKind];
+
+            var mesh = subMesh.getMesh();
+            var material = subMesh.getMaterial();
+
+            // Alpha test
+            if (material && material.needAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+                if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
+                    attribs.push(VertexBuffer.UVKind);
+                    defines.push("#define UV1");
+                }
+                if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+                    attribs.push(VertexBuffer.UV2Kind);
+                    defines.push("#define UV2");
+                }
+            }
+
+            // Bones
+            if (mesh.useBones && mesh.computeBonesUsingShaders) {
+                attribs.push(VertexBuffer.MatricesIndicesKind);
+                attribs.push(VertexBuffer.MatricesWeightsKind);
+                if (mesh.numBoneInfluencers > 4) {
+                    attribs.push(VertexBuffer.MatricesIndicesExtraKind);
+                    attribs.push(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"],
+                    ["diffuseSampler"], join);
+            }
+
+            return this._effect.isReady();
+        }
+
+        public getShadowMap(): RenderTargetTexture {
+            return this._shadowMap;
+        }
+
+        public getShadowMapForRendering(): RenderTargetTexture {
+            if (this._shadowMap2) {
+                return this._shadowMap2;
+            }
+
+            return this._shadowMap;
+        }
+
+        public getLight(): IShadowLight {
+            return this._light;
+        }
+
+        // Methods
+        public getTransformMatrix(): Matrix {
+            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;
+            Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
+
+            if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
+                this._lightDirection.z = 0.0000000000001; // Need 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();
+
+                Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
+
+                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
+
+                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+            }
+
+            return this._transformMatrix;
+        }
+
+        public getDarkness(): number {
+            return this._darkness;
+        }
+
+        public setDarkness(darkness: number): void {
+            if (darkness >= 1.0)
+                this._darkness = 1.0;
+            else if (darkness <= 0.0)
+                this._darkness = 0.0;
+            else
+                this._darkness = darkness;
+        }
+
+        public setTransparencyShadow(hasShadow: boolean): void {
+            this._transparencyShadow = hasShadow;
+        }
+
+        private _packHalf(depth: number): Vector2 {
+            var scale = depth * 255.0;
+            var fract = scale - Math.floor(scale);
+
+            return new Vector2(depth - fract / 255.0, fract);
+        }
+
+        public dispose(): void {
+            this._shadowMap.dispose();
+
+            if (this._shadowMap2) {
+                this._shadowMap2.dispose();
+            }
+
+            if (this._downSamplePostprocess) {
+                this._downSamplePostprocess.dispose();
+            }
+
+            if (this._boxBlurPostprocess) {
+                this._boxBlurPostprocess.dispose();
+            }
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            serializationObject.lightId = this._light.id;
+            serializationObject.mapSize = this.getShadowMap().getRenderSize();
+            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
+            serializationObject.usePoissonSampling = this.usePoissonSampling;
+
+            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;
+        }
+
+        public static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
+            //casting to point light, as light is missing the position attr and typescript complains.
+            var light = <PointLight>scene.getLightByID(parsedShadowGenerator.lightId);
+            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
+
+            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
+                var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
+
+                shadowGenerator.getShadowMap().renderList.push(mesh);
+            }
+
+            if (parsedShadowGenerator.usePoissonSampling) {
+                shadowGenerator.usePoissonSampling = true;
+            } else if (parsedShadowGenerator.useVarianceShadowMap) {
+                shadowGenerator.useVarianceShadowMap = true;
+            } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
+                shadowGenerator.useBlurVarianceShadowMap = true;
+
+                if (parsedShadowGenerator.blurScale) {
+                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
+                }
+
+                if (parsedShadowGenerator.blurBoxOffset) {
+                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
+                }
+            }
+
+            if (parsedShadowGenerator.bias !== undefined) {
+                shadowGenerator.bias = parsedShadowGenerator.bias;
+            }
+
+            return shadowGenerator;
+        }
+    }
 } 

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

@@ -86,7 +86,7 @@ var BABYLON;
             serializationObject.specular = this.specular.asArray();
             return serializationObject;
         };
-        Light.ParseLight = function (parsedLight, scene) {
+        Light.Parse = function (parsedLight, scene) {
             var light;
             switch (parsedLight.type) {
                 case 0:
@@ -128,7 +128,7 @@ var BABYLON;
             if (parsedLight.animations) {
                 for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
                     var parsedAnimation = parsedLight.animations[animationIndex];
-                    light.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
+                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                 }
             }
             if (parsedLight.autoAnimate) {

+ 199 - 199
src/Lights/babylon.light.ts

@@ -1,199 +1,199 @@
-module BABYLON {
-
-    export interface IShadowLight {
-        id: string;
-        position: Vector3;
-        transformedPosition: Vector3;
-        name: string;
-
-        computeTransformedPosition(): boolean;
-        getScene(): Scene;
-
-        setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array<AbstractMesh>): void;
-
-        supportsVSM(): boolean;
-        needRefreshPerFrame(): boolean;
-        needCube(): boolean;
-
-        getShadowDirection(faceIndex?: number): Vector3;
-
-        _shadowGenerator: ShadowGenerator;
-    }
-
-    export class Light extends Node {
-        public diffuse = new Color3(1.0, 1.0, 1.0);
-        public specular = new Color3(1.0, 1.0, 1.0);
-        public intensity = 1.0;
-        public range = Number.MAX_VALUE;
-        public includeOnlyWithLayerMask = 0;
-        public includedOnlyMeshes = new Array<AbstractMesh>();
-        public excludedMeshes = new Array<AbstractMesh>();
-        public excludeWithLayerMask = 0;
-
-        public _shadowGenerator: ShadowGenerator;
-        private _parentedWorldMatrix: Matrix;
-        public _excludedMeshesIds = new Array<string>();
-        public _includedOnlyMeshesIds = new Array<string>();
-
-        constructor(name: string, scene: Scene) {
-            super(name, scene);
-
-            scene.addLight(this);
-        }
-
-        public getShadowGenerator(): ShadowGenerator {
-            return this._shadowGenerator;
-        }
-
-        public getAbsolutePosition(): Vector3 {
-            return Vector3.Zero();
-        }
-
-        public transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void {
-        }
-
-        public _getWorldMatrix(): Matrix {
-            return Matrix.Identity();
-        }
-
-        public canAffectMesh(mesh: AbstractMesh): boolean {
-            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;
-        }
-
-        public getWorldMatrix(): Matrix {
-            this._currentRenderId = this.getScene().getRenderId();
-
-            var worldMatrix = this._getWorldMatrix();
-
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._parentedWorldMatrix) {
-                    this._parentedWorldMatrix = Matrix.Identity();
-                }
-
-                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
-
-                this._markSyncedWithParent();
-
-                return this._parentedWorldMatrix;
-            }
-
-            return worldMatrix;
-        }
-
-        public dispose(): void {
-            if (this._shadowGenerator) {
-                this._shadowGenerator.dispose();
-                this._shadowGenerator = null;
-            }
-
-            // Animations
-            this.getScene().stopAnimation(this);
-
-            // Remove from scene
-            this.getScene().removeLight(this);
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.tags = Tags.GetTags(this);
-
-            if (this.intensity) {
-                serializationObject.intensity = this.intensity;
-            }
-
-            serializationObject.range = this.range;
-
-            serializationObject.diffuse = this.diffuse.asArray();
-            serializationObject.specular = this.specular.asArray();
-
-            return serializationObject;
-        }
-
-        public static ParseLight(parsedLight: any, scene: Scene): Light {
-            var light;
-
-            switch (parsedLight.type) {
-                case 0:
-                    light = new PointLight(parsedLight.name, Vector3.FromArray(parsedLight.position), scene);
-                    break;
-                case 1:
-                    light = new DirectionalLight(parsedLight.name, Vector3.FromArray(parsedLight.direction), scene);
-                    light.position = Vector3.FromArray(parsedLight.position);
-                    break;
-                case 2:
-                    light = new SpotLight(parsedLight.name, Vector3.FromArray(parsedLight.position), Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
-                    break;
-                case 3:
-                    light = new HemisphericLight(parsedLight.name, Vector3.FromArray(parsedLight.direction), scene);
-                    light.groundColor = Color3.FromArray(parsedLight.groundColor);
-                    break;
-            }
-
-            light.id = parsedLight.id;
-
-            Tags.AddTagsTo(light, parsedLight.tags);
-
-            if (parsedLight.intensity !== undefined) {
-                light.intensity = parsedLight.intensity;
-            }
-
-            if (parsedLight.range) {
-                light.range = parsedLight.range;
-            }
-
-            light.diffuse = Color3.FromArray(parsedLight.diffuse);
-            light.specular = Color3.FromArray(parsedLight.specular);
-
-            if (parsedLight.excludedMeshesIds) {
-                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
-            }
-
-            // Parent
-            if (parsedLight.parentId) {
-                light._waitingParentId = parsedLight.parentId;
-            }
-
-            if (parsedLight.includedOnlyMeshesIds) {
-                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
-            }
-
-            // Animations
-            if (parsedLight.animations) {
-                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedLight.animations[animationIndex];
-
-                    light.animations.push(Animation.ParseAnimation(parsedAnimation));
-                }
-            }
-
-            if (parsedLight.autoAnimate) {
-                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
-            }
-            
-            return light;
-        }
-    }
-} 
+module BABYLON {
+
+    export interface IShadowLight {
+        id: string;
+        position: Vector3;
+        transformedPosition: Vector3;
+        name: string;
+
+        computeTransformedPosition(): boolean;
+        getScene(): Scene;
+
+        setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array<AbstractMesh>): void;
+
+        supportsVSM(): boolean;
+        needRefreshPerFrame(): boolean;
+        needCube(): boolean;
+
+        getShadowDirection(faceIndex?: number): Vector3;
+
+        _shadowGenerator: ShadowGenerator;
+    }
+
+    export class Light extends Node {
+        public diffuse = new Color3(1.0, 1.0, 1.0);
+        public specular = new Color3(1.0, 1.0, 1.0);
+        public intensity = 1.0;
+        public range = Number.MAX_VALUE;
+        public includeOnlyWithLayerMask = 0;
+        public includedOnlyMeshes = new Array<AbstractMesh>();
+        public excludedMeshes = new Array<AbstractMesh>();
+        public excludeWithLayerMask = 0;
+
+        public _shadowGenerator: ShadowGenerator;
+        private _parentedWorldMatrix: Matrix;
+        public _excludedMeshesIds = new Array<string>();
+        public _includedOnlyMeshesIds = new Array<string>();
+
+        constructor(name: string, scene: Scene) {
+            super(name, scene);
+
+            scene.addLight(this);
+        }
+
+        public getShadowGenerator(): ShadowGenerator {
+            return this._shadowGenerator;
+        }
+
+        public getAbsolutePosition(): Vector3 {
+            return Vector3.Zero();
+        }
+
+        public transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void {
+        }
+
+        public _getWorldMatrix(): Matrix {
+            return Matrix.Identity();
+        }
+
+        public canAffectMesh(mesh: AbstractMesh): boolean {
+            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;
+        }
+
+        public getWorldMatrix(): Matrix {
+            this._currentRenderId = this.getScene().getRenderId();
+
+            var worldMatrix = this._getWorldMatrix();
+
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._parentedWorldMatrix) {
+                    this._parentedWorldMatrix = Matrix.Identity();
+                }
+
+                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
+
+                this._markSyncedWithParent();
+
+                return this._parentedWorldMatrix;
+            }
+
+            return worldMatrix;
+        }
+
+        public dispose(): void {
+            if (this._shadowGenerator) {
+                this._shadowGenerator.dispose();
+                this._shadowGenerator = null;
+            }
+
+            // Animations
+            this.getScene().stopAnimation(this);
+
+            // Remove from scene
+            this.getScene().removeLight(this);
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.tags = Tags.GetTags(this);
+
+            if (this.intensity) {
+                serializationObject.intensity = this.intensity;
+            }
+
+            serializationObject.range = this.range;
+
+            serializationObject.diffuse = this.diffuse.asArray();
+            serializationObject.specular = this.specular.asArray();
+
+            return serializationObject;
+        }
+
+        public static Parse(parsedLight: any, scene: Scene): Light {
+            var light;
+
+            switch (parsedLight.type) {
+                case 0:
+                    light = new PointLight(parsedLight.name, Vector3.FromArray(parsedLight.position), scene);
+                    break;
+                case 1:
+                    light = new DirectionalLight(parsedLight.name, Vector3.FromArray(parsedLight.direction), scene);
+                    light.position = Vector3.FromArray(parsedLight.position);
+                    break;
+                case 2:
+                    light = new SpotLight(parsedLight.name, Vector3.FromArray(parsedLight.position), Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
+                    break;
+                case 3:
+                    light = new HemisphericLight(parsedLight.name, Vector3.FromArray(parsedLight.direction), scene);
+                    light.groundColor = Color3.FromArray(parsedLight.groundColor);
+                    break;
+            }
+
+            light.id = parsedLight.id;
+
+            Tags.AddTagsTo(light, parsedLight.tags);
+
+            if (parsedLight.intensity !== undefined) {
+                light.intensity = parsedLight.intensity;
+            }
+
+            if (parsedLight.range) {
+                light.range = parsedLight.range;
+            }
+
+            light.diffuse = Color3.FromArray(parsedLight.diffuse);
+            light.specular = Color3.FromArray(parsedLight.specular);
+
+            if (parsedLight.excludedMeshesIds) {
+                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
+            }
+
+            // Parent
+            if (parsedLight.parentId) {
+                light._waitingParentId = parsedLight.parentId;
+            }
+
+            if (parsedLight.includedOnlyMeshesIds) {
+                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
+            }
+
+            // Animations
+            if (parsedLight.animations) {
+                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedLight.animations[animationIndex];
+
+                    light.animations.push(Animation.Parse(parsedAnimation));
+                }
+            }
+
+            if (parsedLight.autoAnimate) {
+                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
+            }
+            
+            return light;
+        }
+    }
+} 

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

@@ -6,7 +6,7 @@ var BABYLON;
             for (var index = 0; index < parsedData.materials.length; index++) {
                 var parsedMaterial = parsedData.materials[index];
                 if (parsedMaterial.id === id) {
-                    return BABYLON.Material.ParseMaterial(parsedMaterial, scene, rootUrl);
+                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
                 }
             }
             return null;
@@ -52,31 +52,31 @@ var BABYLON;
                                     }
                                     else {
                                         parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
-                                            if (parsedGeometryData.id == parsedMesh.geometryId) {
+                                            if (parsedGeometryData.id === parsedMesh.geometryId) {
                                                 switch (geometryType) {
                                                     case "boxes":
-                                                        BABYLON.Geometry.Primitives.Box.ParseBox(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "spheres":
-                                                        BABYLON.Geometry.Primitives.Sphere.ParseSphere(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "cylinders":
-                                                        BABYLON.Geometry.Primitives.Cylinder.ParseCylinder(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "toruses":
-                                                        BABYLON.Geometry.Primitives.Torus.ParseTorus(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "grounds":
-                                                        BABYLON.Geometry.Primitives.Ground.ParseGround(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "planes":
-                                                        BABYLON.Geometry.Primitives.Plane.ParsePlane(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "torusKnots":
-                                                        BABYLON.Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedGeometryData, scene);
+                                                        BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
                                                         break;
                                                     case "vertexData":
-                                                        BABYLON.Geometry.ParseGeometry(parsedGeometryData, scene, rootUrl);
+                                                        BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
                                                         break;
                                                 }
                                                 found = true;
@@ -102,7 +102,7 @@ var BABYLON;
                                             parseMaterialById(subMatId, parsedData, scene, rootUrl);
                                         }
                                         loadedMaterialsIds.push(parsedMultiMaterial.id);
-                                        parsedMultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
+                                        parsedMultiMaterial.Parse(parsedMultiMaterial, scene);
                                         materialFound = true;
                                         break;
                                     }
@@ -122,13 +122,13 @@ var BABYLON;
                                 for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
                                     var parsedSkeleton = parsedData.skeletons[skeletonIndex];
                                     if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                        skeletons.push(BABYLON.Skeleton.ParseSkeleton(parsedSkeleton, scene));
+                                        skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
                                         loadedSkeletonsIds.push(parsedSkeleton.id);
                                     }
                                 }
                             }
                         }
-                        var mesh = BABYLON.Mesh.ParseMesh(parsedMesh, scene, rootUrl);
+                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                         meshes.push(mesh);
                     }
                 }
@@ -154,7 +154,7 @@ var BABYLON;
                     for (index = 0; index < parsedData.particleSystems.length; index++) {
                         var parsedParticleSystem = parsedData.particleSystems[index];
                         if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                            particleSystems.push(BABYLON.ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl));
+                            particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
                         }
                     }
                 }
@@ -200,26 +200,26 @@ var BABYLON;
                 var index;
                 for (index = 0; index < parsedData.lights.length; index++) {
                     var parsedLight = parsedData.lights[index];
-                    BABYLON.Light.ParseLight(parsedLight, scene);
+                    BABYLON.Light.Parse(parsedLight, scene);
                 }
                 // Materials
                 if (parsedData.materials) {
                     for (index = 0; index < parsedData.materials.length; index++) {
                         var parsedMaterial = parsedData.materials[index];
-                        BABYLON.Material.ParseMaterial(parsedMaterial, scene, rootUrl);
+                        BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
                     }
                 }
                 if (parsedData.multiMaterials) {
                     for (index = 0; index < parsedData.multiMaterials.length; index++) {
                         var parsedMultiMaterial = parsedData.multiMaterials[index];
-                        BABYLON.MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
+                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
                     }
                 }
                 // Skeletons
                 if (parsedData.skeletons) {
                     for (index = 0; index < parsedData.skeletons.length; index++) {
                         var parsedSkeleton = parsedData.skeletons[index];
-                        BABYLON.Skeleton.ParseSkeleton(parsedSkeleton, scene);
+                        BABYLON.Skeleton.Parse(parsedSkeleton, scene);
                     }
                 }
                 // Geometries
@@ -230,7 +230,7 @@ var BABYLON;
                     if (boxes) {
                         for (index = 0; index < boxes.length; index++) {
                             var parsedBox = boxes[index];
-                            BABYLON.Geometry.Primitives.Box.ParseBox(parsedBox, scene);
+                            BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
                         }
                     }
                     // Spheres
@@ -238,7 +238,7 @@ var BABYLON;
                     if (spheres) {
                         for (index = 0; index < spheres.length; index++) {
                             var parsedSphere = spheres[index];
-                            BABYLON.Geometry.Primitives.Sphere.ParseSphere(parsedSphere, scene);
+                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
                         }
                     }
                     // Cylinders
@@ -246,7 +246,7 @@ var BABYLON;
                     if (cylinders) {
                         for (index = 0; index < cylinders.length; index++) {
                             var parsedCylinder = cylinders[index];
-                            BABYLON.Geometry.Primitives.Cylinder.ParseCylinder(parsedCylinder, scene);
+                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
                         }
                     }
                     // Toruses
@@ -254,7 +254,7 @@ var BABYLON;
                     if (toruses) {
                         for (index = 0; index < toruses.length; index++) {
                             var parsedTorus = toruses[index];
-                            BABYLON.Geometry.Primitives.Torus.ParseTorus(parsedTorus, scene);
+                            BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
                         }
                     }
                     // Grounds
@@ -262,7 +262,7 @@ var BABYLON;
                     if (grounds) {
                         for (index = 0; index < grounds.length; index++) {
                             var parsedGround = grounds[index];
-                            BABYLON.Geometry.Primitives.Ground.ParseGround(parsedGround, scene);
+                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
                         }
                     }
                     // Planes
@@ -270,7 +270,7 @@ var BABYLON;
                     if (planes) {
                         for (index = 0; index < planes.length; index++) {
                             var parsedPlane = planes[index];
-                            BABYLON.Geometry.Primitives.Plane.ParsePlane(parsedPlane, scene);
+                            BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
                         }
                     }
                     // TorusKnots
@@ -278,7 +278,7 @@ var BABYLON;
                     if (torusKnots) {
                         for (index = 0; index < torusKnots.length; index++) {
                             var parsedTorusKnot = torusKnots[index];
-                            BABYLON.Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedTorusKnot, scene);
+                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
                         }
                     }
                     // VertexData
@@ -286,19 +286,19 @@ var BABYLON;
                     if (vertexData) {
                         for (index = 0; index < vertexData.length; index++) {
                             var parsedVertexData = vertexData[index];
-                            BABYLON.Geometry.ParseGeometry(parsedVertexData, scene, rootUrl);
+                            BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
                         }
                     }
                 }
                 // Meshes
                 for (index = 0; index < parsedData.meshes.length; index++) {
                     var parsedMesh = parsedData.meshes[index];
-                    BABYLON.Mesh.ParseMesh(parsedMesh, scene, rootUrl);
+                    BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                 }
                 // Cameras
                 for (index = 0; index < parsedData.cameras.length; index++) {
                     var parsedCamera = parsedData.cameras[index];
-                    BABYLON.Camera.ParseCamera(parsedCamera, scene);
+                    BABYLON.Camera.Parse(parsedCamera, scene);
                 }
                 if (parsedData.activeCameraID) {
                     scene.setActiveCameraByID(parsedData.activeCameraID);
@@ -323,7 +323,7 @@ var BABYLON;
                     for (index = 0; index < parsedData.sounds.length; index++) {
                         var parsedSound = parsedData.sounds[index];
                         if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                            BABYLON.Sound.ParseSound(parsedSound, scene, rootUrl);
+                            BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
                         }
                         else {
                             var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
@@ -338,7 +338,7 @@ var BABYLON;
                         mesh._waitingParentId = undefined;
                     }
                     if (mesh._waitingActions) {
-                        BABYLON.ActionManager.ParseActions(mesh._waitingActions, mesh, scene);
+                        BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
                         mesh._waitingActions = undefined;
                     }
                 }
@@ -354,26 +354,26 @@ var BABYLON;
                 if (parsedData.particleSystems) {
                     for (index = 0; index < parsedData.particleSystems.length; index++) {
                         var parsedParticleSystem = parsedData.particleSystems[index];
-                        BABYLON.ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl);
+                        BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
                     }
                 }
                 // Lens flares
                 if (parsedData.lensFlareSystems) {
                     for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
                         var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                        BABYLON.LensFlareSystem.ParseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
+                        BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
                     }
                 }
                 // Shadows
                 if (parsedData.shadowGenerators) {
                     for (index = 0; index < parsedData.shadowGenerators.length; index++) {
                         var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                        BABYLON.ShadowGenerator.ParseShadowGenerator(parsedShadowGenerator, scene);
+                        BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
                     }
                 }
                 // Actions (scene)
                 if (parsedData.actions) {
-                    BABYLON.ActionManager.ParseActions(parsedData.actions, null, scene);
+                    BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
                 }
                 // Finish
                 return true;

+ 433 - 433
src/Loading/Plugins/babylon.babylonFileLoader.ts

@@ -1,433 +1,433 @@
-module BABYLON.Internals {
-
-    var parseMaterialById = (id, parsedData, scene, rootUrl) => {
-        for (var index = 0; index < parsedData.materials.length; index++) {
-            var parsedMaterial = parsedData.materials[index];
-            if (parsedMaterial.id === id) {
-                return BABYLON.Material.ParseMaterial(parsedMaterial, scene, rootUrl);
-            }
-        }
-
-        return null;
-    };
-
-    var isDescendantOf = (mesh, names, hierarchyIds) => {
-        names = (names instanceof Array) ? names : [names];
-        for (var i in names) {
-            if (mesh.name === names[i]) {
-                hierarchyIds.push(mesh.id);
-                return true;
-            }
-        }
-
-        if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
-            hierarchyIds.push(mesh.id);
-            return true;
-        }
-
-        return false;
-    };
-
-    BABYLON.SceneLoader.RegisterPlugin({
-        extensions: ".babylon",
-        importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]): boolean => {
-            var parsedData = JSON.parse(data);
-
-            var loadedSkeletonsIds = [];
-            var loadedMaterialsIds = [];
-            var hierarchyIds = [];
-            var index: number;
-            for (index = 0; index < parsedData.meshes.length; 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: boolean = false;
-                            ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType: string) => {
-                                if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
-                                    return;
-                                } else {
-                                    parsedData.geometries[geometryType].forEach((parsedGeometryData) => {
-                                        if (parsedGeometryData.id == parsedMesh.geometryId) {
-                                            switch (geometryType) {
-                                                case "boxes":
-                                                    Geometry.Primitives.Box.ParseBox(parsedGeometryData, scene);
-                                                    break;
-                                                case "spheres":
-                                                    Geometry.Primitives.Sphere.ParseSphere(parsedGeometryData, scene);
-                                                    break;
-                                                case "cylinders":
-                                                    Geometry.Primitives.Cylinder.ParseCylinder(parsedGeometryData, scene);
-                                                    break;
-                                                case "toruses":
-                                                    Geometry.Primitives.Torus.ParseTorus(parsedGeometryData, scene);
-                                                    break;
-                                                case "grounds":
-                                                    Geometry.Primitives.Ground.ParseGround(parsedGeometryData, scene);
-                                                    break;
-                                                case "planes":
-                                                    Geometry.Primitives.Plane.ParsePlane(parsedGeometryData, scene);
-                                                    break;
-                                                case "torusKnots":
-                                                    Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedGeometryData, scene);
-                                                    break;
-                                                case "vertexData":
-                                                    Geometry.ParseGeometry(parsedGeometryData, scene, rootUrl);
-                                                    break;
-                                            }
-                                            found = true;
-                                        }
-                                    });
-
-                                }
-                            });
-                            if (!found) {
-                                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; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
-                                var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
-                                if (parsedMultiMaterial.id == parsedMesh.materialId) {
-                                    for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
-                                        var subMatId = parsedMultiMaterial.materials[matIndex];
-                                        loadedMaterialsIds.push(subMatId);
-                                        parseMaterialById(subMatId, parsedData, scene, rootUrl);
-                                    }
-
-                                    loadedMaterialsIds.push(parsedMultiMaterial.id);
-                                    parsedMultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
-                                    materialFound = true;
-                                    break;
-                                }
-                            }
-                        }
-
-                        if (!materialFound) {
-                            loadedMaterialsIds.push(parsedMesh.materialId);
-                            if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
-                                Tools.Warn("Material not found for mesh " + parsedMesh.id);
-                            }
-                        }
-                    }
-
-                    // Skeleton ?
-                    if (parsedMesh.skeletonId > -1 && scene.skeletons) {
-                        var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
-
-                        if (!skeletonAlreadyLoaded) {
-                            for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
-                                var parsedSkeleton = parsedData.skeletons[skeletonIndex];
-
-                                if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                    skeletons.push(Skeleton.ParseSkeleton(parsedSkeleton, scene));
-                                    loadedSkeletonsIds.push(parsedSkeleton.id);
-                                }
-                            }
-                        }
-                    }
-
-                    var mesh = Mesh.ParseMesh(parsedMesh, scene, rootUrl);
-                    meshes.push(mesh);
-                }
-            }
-
-            // Connecting parents
-            var currentMesh: AbstractMesh;
-            for (index = 0; index < scene.meshes.length; index++) {
-                currentMesh = scene.meshes[index];
-                if (currentMesh._waitingParentId) {
-                    currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
-                    currentMesh._waitingParentId = undefined;
-                }
-            }
-
-            // freeze world matrix application
-            for (index = 0; index < scene.meshes.length; index++) {
-                currentMesh = scene.meshes[index];
-                if (currentMesh._waitingFreezeWorldMatrix) {
-                    currentMesh.freezeWorldMatrix();
-                    currentMesh._waitingFreezeWorldMatrix = undefined;
-                }
-            }
-
-            // Particles
-            if (parsedData.particleSystems) {
-                for (index = 0; index < parsedData.particleSystems.length; index++) {
-                    var parsedParticleSystem = parsedData.particleSystems[index];
-
-                    if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                        particleSystems.push(ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl));
-                    }
-                }
-            }
-
-            return true;
-        },
-        load: (scene: Scene, data: string, rootUrl: string): boolean => {
-            var parsedData = JSON.parse(data);
-
-            // Scene
-            scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
-            scene.autoClear = parsedData.autoClear;
-            scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
-            scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
-            if (parsedData.gravity) {
-                scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
-            }
-            
-            // Fog
-            if (parsedData.fogMode && parsedData.fogMode !== 0) {
-                scene.fogMode = parsedData.fogMode;
-                scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
-                scene.fogStart = parsedData.fogStart;
-                scene.fogEnd = parsedData.fogEnd;
-                scene.fogDensity = parsedData.fogDensity;
-            }
-            
-            //Physics
-            if (parsedData.physicsEnabled) {
-                var physicsPlugin;
-                if (parsedData.physicsEngine === "cannon") {
-                    physicsPlugin = new BABYLON.CannonJSPlugin();
-                } else if (parsedData.physicsEngine === "oimo") {
-                    physicsPlugin = new BABYLON.OimoJSPlugin();
-                }
-                //else - default engine, which is currently oimo
-                var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
-                scene.enablePhysics(physicsGravity, physicsPlugin);
-            }
-            
-            //collisions, if defined. otherwise, default is true
-            if (parsedData.collisionsEnabled != undefined) {
-                scene.collisionsEnabled = parsedData.collisionsEnabled;
-            }
-            scene.workerCollisions = !!parsedData.workerCollisions;            
-
-            // Lights
-            var index: number;
-            for (index = 0; index < parsedData.lights.length; index++) {
-                var parsedLight = parsedData.lights[index];
-                Light.ParseLight(parsedLight, scene);
-            }
-
-            // Materials
-            if (parsedData.materials) {
-                for (index = 0; index < parsedData.materials.length; index++) {
-                    var parsedMaterial = parsedData.materials[index];
-                    Material.ParseMaterial(parsedMaterial, scene, rootUrl);
-                }
-            }
-
-            if (parsedData.multiMaterials) {
-                for (index = 0; index < parsedData.multiMaterials.length; index++) {
-                    var parsedMultiMaterial = parsedData.multiMaterials[index];
-                    MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
-                }
-            }
-
-            // Skeletons
-            if (parsedData.skeletons) {
-                for (index = 0; index < parsedData.skeletons.length; index++) {
-                    var parsedSkeleton = parsedData.skeletons[index];
-                    Skeleton.ParseSkeleton(parsedSkeleton, scene);
-                }
-            }
-
-            // Geometries
-            var geometries = parsedData.geometries;
-            if (geometries) {
-                // Boxes
-                var boxes = geometries.boxes;
-                if (boxes) {
-                    for (index = 0; index < boxes.length; index++) {
-                        var parsedBox = boxes[index];
-                        Geometry.Primitives.Box.ParseBox(parsedBox, scene);
-                    }
-                }
-
-                // Spheres
-                var spheres = geometries.spheres;
-                if (spheres) {
-                    for (index = 0; index < spheres.length; index++) {
-                        var parsedSphere = spheres[index];
-                        Geometry.Primitives.Sphere.ParseSphere(parsedSphere, scene);
-                    }
-                }
-
-                // Cylinders
-                var cylinders = geometries.cylinders;
-                if (cylinders) {
-                    for (index = 0; index < cylinders.length; index++) {
-                        var parsedCylinder = cylinders[index];
-                        Geometry.Primitives.Cylinder.ParseCylinder(parsedCylinder, scene);
-                    }
-                }
-
-                // Toruses
-                var toruses = geometries.toruses;
-                if (toruses) {
-                    for (index = 0; index < toruses.length; index++) {
-                        var parsedTorus = toruses[index];
-                        Geometry.Primitives.Torus.ParseTorus(parsedTorus, scene);
-                    }
-                }
-
-                // Grounds
-                var grounds = geometries.grounds;
-                if (grounds) {
-                    for (index = 0; index < grounds.length; index++) {
-                        var parsedGround = grounds[index];
-                        Geometry.Primitives.Ground.ParseGround(parsedGround, scene);
-                    }
-                }
-
-                // Planes
-                var planes = geometries.planes;
-                if (planes) {
-                    for (index = 0; index < planes.length; index++) {
-                        var parsedPlane = planes[index];
-                        Geometry.Primitives.Plane.ParsePlane(parsedPlane, scene);
-                    }
-                }
-
-                // TorusKnots
-                var torusKnots = geometries.torusKnots;
-                if (torusKnots) {
-                    for (index = 0; index < torusKnots.length; index++) {
-                        var parsedTorusKnot = torusKnots[index];
-                        Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedTorusKnot, scene);
-                    }
-                }
-
-                // VertexData
-                var vertexData = geometries.vertexData;
-                if (vertexData) {
-                    for (index = 0; index < vertexData.length; index++) {
-                        var parsedVertexData = vertexData[index];
-                        Geometry.ParseGeometry(parsedVertexData, scene, rootUrl);
-                    }
-                }
-            }
-
-            // Meshes
-            for (index = 0; index < parsedData.meshes.length; index++) {
-                var parsedMesh = parsedData.meshes[index];
-                Mesh.ParseMesh(parsedMesh, scene, rootUrl);
-            }
-
-            // Cameras
-            for (index = 0; index < parsedData.cameras.length; index++) {
-                var parsedCamera = parsedData.cameras[index];
-                Camera.ParseCamera(parsedCamera, scene);
-            }
-
-            if (parsedData.activeCameraID) {
-                scene.setActiveCameraByID(parsedData.activeCameraID);
-            }
-
-            // Browsing all the graph to connect the dots
-            for (index = 0; index < scene.cameras.length; index++) {
-                var camera = scene.cameras[index];
-                if (camera._waitingParentId) {
-                    camera.parent = scene.getLastEntryByID(camera._waitingParentId);
-                    camera._waitingParentId = undefined;
-                }
-            }
-
-            for (index = 0; index < scene.lights.length; index++) {
-                var light = scene.lights[index];
-                if (light._waitingParentId) {
-                    light.parent = scene.getLastEntryByID(light._waitingParentId);
-                    light._waitingParentId = undefined;
-                }
-            }
-
-            // Sounds
-            if (AudioEngine && parsedData.sounds) {
-                for (index = 0; index < parsedData.sounds.length; index++) {
-                    var parsedSound = parsedData.sounds[index];
-                    if (Engine.audioEngine.canUseWebAudio) {
-                        Sound.ParseSound(parsedSound, scene, rootUrl);
-                    }
-                    else {
-                        var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
-                    }
-                }
-            }
-
-            // Connect parents & children and parse actions
-            for (index = 0; index < scene.meshes.length; index++) {
-                var mesh = scene.meshes[index];
-                if (mesh._waitingParentId) {
-                    mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
-                    mesh._waitingParentId = undefined;
-                }
-                if (mesh._waitingActions) {
-                    ActionManager.ParseActions(mesh._waitingActions, mesh, scene);
-                    mesh._waitingActions = undefined;
-                }
-            }
-
-            // freeze world matrix application
-            for (index = 0; index < scene.meshes.length; index++) {
-                var currentMesh = scene.meshes[index];
-                if (currentMesh._waitingFreezeWorldMatrix) {
-                    currentMesh.freezeWorldMatrix();
-                    currentMesh._waitingFreezeWorldMatrix = undefined;
-                }
-            }
-
-            // Particles Systems
-            if (parsedData.particleSystems) {
-                for (index = 0; index < parsedData.particleSystems.length; index++) {
-                    var parsedParticleSystem = parsedData.particleSystems[index];
-                    ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl);
-                }
-            }
-
-            // Lens flares
-            if (parsedData.lensFlareSystems) {
-                for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
-                    var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                    LensFlareSystem.ParseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
-                }
-            }
-
-            // Shadows
-            if (parsedData.shadowGenerators) {
-                for (index = 0; index < parsedData.shadowGenerators.length; index++) {
-                    var parsedShadowGenerator = parsedData.shadowGenerators[index];
-
-                    ShadowGenerator.ParseShadowGenerator(parsedShadowGenerator, scene);
-                }
-            }
-
-            // Actions (scene)
-            if (parsedData.actions) {
-                ActionManager.ParseActions(parsedData.actions, null, scene);
-            }
-
-            // Finish
-            return true;
-        }
-    });
-}
-
-
-
+module BABYLON.Internals {
+
+    var parseMaterialById = (id, parsedData, scene, rootUrl) => {
+        for (var index = 0; index < parsedData.materials.length; index++) {
+            var parsedMaterial = parsedData.materials[index];
+            if (parsedMaterial.id === id) {
+                return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+            }
+        }
+
+        return null;
+    };
+
+    var isDescendantOf = (mesh, names, hierarchyIds) => {
+        names = (names instanceof Array) ? names : [names];
+        for (var i in names) {
+            if (mesh.name === names[i]) {
+                hierarchyIds.push(mesh.id);
+                return true;
+            }
+        }
+
+        if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
+            hierarchyIds.push(mesh.id);
+            return true;
+        }
+
+        return false;
+    };
+
+    BABYLON.SceneLoader.RegisterPlugin({
+        extensions: ".babylon",
+        importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]): boolean => {
+            var parsedData = JSON.parse(data);
+
+            var loadedSkeletonsIds = [];
+            var loadedMaterialsIds = [];
+            var hierarchyIds = [];
+            var index: number;
+            for (index = 0; index < parsedData.meshes.length; 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: boolean = false;
+                            ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType: string) => {
+                                if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
+                                    return;
+                                } else {
+                                    parsedData.geometries[geometryType].forEach((parsedGeometryData) => {
+                                        if (parsedGeometryData.id === parsedMesh.geometryId) {
+                                            switch (geometryType) {
+                                                case "boxes":
+                                                    Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "spheres":
+                                                    Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "cylinders":
+                                                    Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "toruses":
+                                                    Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "grounds":
+                                                    Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "planes":
+                                                    Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "torusKnots":
+                                                    Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
+                                                    break;
+                                                case "vertexData":
+                                                    Geometry.Parse(parsedGeometryData, scene, rootUrl);
+                                                    break;
+                                            }
+                                            found = true;
+                                        }
+                                    });
+
+                                }
+                            });
+                            if (!found) {
+                                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; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
+                                var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
+                                if (parsedMultiMaterial.id == parsedMesh.materialId) {
+                                    for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
+                                        var subMatId = parsedMultiMaterial.materials[matIndex];
+                                        loadedMaterialsIds.push(subMatId);
+                                        parseMaterialById(subMatId, parsedData, scene, rootUrl);
+                                    }
+
+                                    loadedMaterialsIds.push(parsedMultiMaterial.id);
+                                    parsedMultiMaterial.Parse(parsedMultiMaterial, scene);
+                                    materialFound = true;
+                                    break;
+                                }
+                            }
+                        }
+
+                        if (!materialFound) {
+                            loadedMaterialsIds.push(parsedMesh.materialId);
+                            if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
+                                Tools.Warn("Material not found for mesh " + parsedMesh.id);
+                            }
+                        }
+                    }
+
+                    // Skeleton ?
+                    if (parsedMesh.skeletonId > -1 && scene.skeletons) {
+                        var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
+
+                        if (!skeletonAlreadyLoaded) {
+                            for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
+                                var parsedSkeleton = parsedData.skeletons[skeletonIndex];
+
+                                if (parsedSkeleton.id === parsedMesh.skeletonId) {
+                                    skeletons.push(Skeleton.Parse(parsedSkeleton, scene));
+                                    loadedSkeletonsIds.push(parsedSkeleton.id);
+                                }
+                            }
+                        }
+                    }
+
+                    var mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
+                    meshes.push(mesh);
+                }
+            }
+
+            // Connecting parents
+            var currentMesh: AbstractMesh;
+            for (index = 0; index < scene.meshes.length; index++) {
+                currentMesh = scene.meshes[index];
+                if (currentMesh._waitingParentId) {
+                    currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
+                    currentMesh._waitingParentId = undefined;
+                }
+            }
+
+            // freeze world matrix application
+            for (index = 0; index < scene.meshes.length; index++) {
+                currentMesh = scene.meshes[index];
+                if (currentMesh._waitingFreezeWorldMatrix) {
+                    currentMesh.freezeWorldMatrix();
+                    currentMesh._waitingFreezeWorldMatrix = undefined;
+                }
+            }
+
+            // Particles
+            if (parsedData.particleSystems) {
+                for (index = 0; index < parsedData.particleSystems.length; index++) {
+                    var parsedParticleSystem = parsedData.particleSystems[index];
+
+                    if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
+                        particleSystems.push(ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
+                    }
+                }
+            }
+
+            return true;
+        },
+        load: (scene: Scene, data: string, rootUrl: string): boolean => {
+            var parsedData = JSON.parse(data);
+
+            // Scene
+            scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
+            scene.autoClear = parsedData.autoClear;
+            scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
+            scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
+            if (parsedData.gravity) {
+                scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
+            }
+            
+            // Fog
+            if (parsedData.fogMode && parsedData.fogMode !== 0) {
+                scene.fogMode = parsedData.fogMode;
+                scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
+                scene.fogStart = parsedData.fogStart;
+                scene.fogEnd = parsedData.fogEnd;
+                scene.fogDensity = parsedData.fogDensity;
+            }
+            
+            //Physics
+            if (parsedData.physicsEnabled) {
+                var physicsPlugin;
+                if (parsedData.physicsEngine === "cannon") {
+                    physicsPlugin = new BABYLON.CannonJSPlugin();
+                } else if (parsedData.physicsEngine === "oimo") {
+                    physicsPlugin = new BABYLON.OimoJSPlugin();
+                }
+                //else - default engine, which is currently oimo
+                var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
+                scene.enablePhysics(physicsGravity, physicsPlugin);
+            }
+            
+            //collisions, if defined. otherwise, default is true
+            if (parsedData.collisionsEnabled != undefined) {
+                scene.collisionsEnabled = parsedData.collisionsEnabled;
+            }
+            scene.workerCollisions = !!parsedData.workerCollisions;            
+
+            // Lights
+            var index: number;
+            for (index = 0; index < parsedData.lights.length; index++) {
+                var parsedLight = parsedData.lights[index];
+                Light.Parse(parsedLight, scene);
+            }
+
+            // Materials
+            if (parsedData.materials) {
+                for (index = 0; index < parsedData.materials.length; index++) {
+                    var parsedMaterial = parsedData.materials[index];
+                    Material.Parse(parsedMaterial, scene, rootUrl);
+                }
+            }
+
+            if (parsedData.multiMaterials) {
+                for (index = 0; index < parsedData.multiMaterials.length; index++) {
+                    var parsedMultiMaterial = parsedData.multiMaterials[index];
+                    Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                }
+            }
+
+            // Skeletons
+            if (parsedData.skeletons) {
+                for (index = 0; index < parsedData.skeletons.length; index++) {
+                    var parsedSkeleton = parsedData.skeletons[index];
+                    Skeleton.Parse(parsedSkeleton, scene);
+                }
+            }
+
+            // Geometries
+            var geometries = parsedData.geometries;
+            if (geometries) {
+                // Boxes
+                var boxes = geometries.boxes;
+                if (boxes) {
+                    for (index = 0; index < boxes.length; index++) {
+                        var parsedBox = boxes[index];
+                        Geometry.Primitives.Box.Parse(parsedBox, scene);
+                    }
+                }
+
+                // Spheres
+                var spheres = geometries.spheres;
+                if (spheres) {
+                    for (index = 0; index < spheres.length; index++) {
+                        var parsedSphere = spheres[index];
+                        Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
+                    }
+                }
+
+                // Cylinders
+                var cylinders = geometries.cylinders;
+                if (cylinders) {
+                    for (index = 0; index < cylinders.length; index++) {
+                        var parsedCylinder = cylinders[index];
+                        Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
+                    }
+                }
+
+                // Toruses
+                var toruses = geometries.toruses;
+                if (toruses) {
+                    for (index = 0; index < toruses.length; index++) {
+                        var parsedTorus = toruses[index];
+                        Geometry.Primitives.Torus.Parse(parsedTorus, scene);
+                    }
+                }
+
+                // Grounds
+                var grounds = geometries.grounds;
+                if (grounds) {
+                    for (index = 0; index < grounds.length; index++) {
+                        var parsedGround = grounds[index];
+                        Geometry.Primitives.Ground.Parse(parsedGround, scene);
+                    }
+                }
+
+                // Planes
+                var planes = geometries.planes;
+                if (planes) {
+                    for (index = 0; index < planes.length; index++) {
+                        var parsedPlane = planes[index];
+                        Geometry.Primitives.Plane.Parse(parsedPlane, scene);
+                    }
+                }
+
+                // TorusKnots
+                var torusKnots = geometries.torusKnots;
+                if (torusKnots) {
+                    for (index = 0; index < torusKnots.length; index++) {
+                        var parsedTorusKnot = torusKnots[index];
+                        Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
+                    }
+                }
+
+                // VertexData
+                var vertexData = geometries.vertexData;
+                if (vertexData) {
+                    for (index = 0; index < vertexData.length; index++) {
+                        var parsedVertexData = vertexData[index];
+                        Geometry.Parse(parsedVertexData, scene, rootUrl);
+                    }
+                }
+            }
+
+            // Meshes
+            for (index = 0; index < parsedData.meshes.length; index++) {
+                var parsedMesh = parsedData.meshes[index];
+                Mesh.Parse(parsedMesh, scene, rootUrl);
+            }
+
+            // Cameras
+            for (index = 0; index < parsedData.cameras.length; index++) {
+                var parsedCamera = parsedData.cameras[index];
+                Camera.Parse(parsedCamera, scene);
+            }
+
+            if (parsedData.activeCameraID) {
+                scene.setActiveCameraByID(parsedData.activeCameraID);
+            }
+
+            // Browsing all the graph to connect the dots
+            for (index = 0; index < scene.cameras.length; index++) {
+                var camera = scene.cameras[index];
+                if (camera._waitingParentId) {
+                    camera.parent = scene.getLastEntryByID(camera._waitingParentId);
+                    camera._waitingParentId = undefined;
+                }
+            }
+
+            for (index = 0; index < scene.lights.length; index++) {
+                var light = scene.lights[index];
+                if (light._waitingParentId) {
+                    light.parent = scene.getLastEntryByID(light._waitingParentId);
+                    light._waitingParentId = undefined;
+                }
+            }
+
+            // Sounds
+            if (AudioEngine && parsedData.sounds) {
+                for (index = 0; index < parsedData.sounds.length; index++) {
+                    var parsedSound = parsedData.sounds[index];
+                    if (Engine.audioEngine.canUseWebAudio) {
+                        Sound.Parse(parsedSound, scene, rootUrl);
+                    }
+                    else {
+                        var emptySound = new Sound(parsedSound.name, null, scene);
+                    }
+                }
+            }
+
+            // Connect parents & children and parse actions
+            for (index = 0; index < scene.meshes.length; index++) {
+                var mesh = scene.meshes[index];
+                if (mesh._waitingParentId) {
+                    mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
+                    mesh._waitingParentId = undefined;
+                }
+                if (mesh._waitingActions) {
+                    ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                    mesh._waitingActions = undefined;
+                }
+            }
+
+            // freeze world matrix application
+            for (index = 0; index < scene.meshes.length; index++) {
+                var currentMesh = scene.meshes[index];
+                if (currentMesh._waitingFreezeWorldMatrix) {
+                    currentMesh.freezeWorldMatrix();
+                    currentMesh._waitingFreezeWorldMatrix = undefined;
+                }
+            }
+
+            // Particles Systems
+            if (parsedData.particleSystems) {
+                for (index = 0; index < parsedData.particleSystems.length; index++) {
+                    var parsedParticleSystem = parsedData.particleSystems[index];
+                    ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                }
+            }
+
+            // Lens flares
+            if (parsedData.lensFlareSystems) {
+                for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
+                    var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                    LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                }
+            }
+
+            // Shadows
+            if (parsedData.shadowGenerators) {
+                for (index = 0; index < parsedData.shadowGenerators.length; index++) {
+                    var parsedShadowGenerator = parsedData.shadowGenerators[index];
+
+                    ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                }
+            }
+
+            // Actions (scene)
+            if (parsedData.actions) {
+                ActionManager.Parse(parsedData.actions, null, scene);
+            }
+
+            // Finish
+            return true;
+        }
+    });
+}
+
+
+

+ 0 - 60
src/Materials/Textures/babylon.baseTexture.js

@@ -130,66 +130,6 @@ var BABYLON;
             BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
             return serializationObject;
         };
-        BaseTexture.ParseCubeTexture = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        };
-        BaseTexture.ParseTexture = function (parsedTexture, scene, rootUrl) {
-            if (parsedTexture.isCube) {
-                return BaseTexture.ParseCubeTexture(parsedTexture, scene, rootUrl);
-            }
-            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
-                return null;
-            }
-            var texture;
-            if (parsedTexture.mirrorPlane) {
-                texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-                texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
-            }
-            else if (parsedTexture.isRenderTarget) {
-                texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-            }
-            else {
-                if (parsedTexture.base64String) {
-                    texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
-                }
-                else {
-                    texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
-                }
-            }
-            texture.name = parsedTexture.name;
-            texture.hasAlpha = parsedTexture.hasAlpha;
-            texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
-            texture.level = parsedTexture.level;
-            texture.coordinatesIndex = parsedTexture.coordinatesIndex;
-            texture.coordinatesMode = parsedTexture.coordinatesMode;
-            texture.uOffset = parsedTexture.uOffset;
-            texture.vOffset = parsedTexture.vOffset;
-            texture.uScale = parsedTexture.uScale;
-            texture.vScale = parsedTexture.vScale;
-            texture.uAng = parsedTexture.uAng;
-            texture.vAng = parsedTexture.vAng;
-            texture.wAng = parsedTexture.wAng;
-            texture.wrapU = parsedTexture.wrapU;
-            texture.wrapV = parsedTexture.wrapV;
-            // Animations
-            if (parsedTexture.animations) {
-                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedTexture.animations[animationIndex];
-                    texture.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
-                }
-            }
-            return texture;
-        };
         return BaseTexture;
     })();
     BABYLON.BaseTexture = BaseTexture;

+ 169 - 237
src/Materials/Textures/babylon.baseTexture.ts

@@ -1,238 +1,170 @@
-module BABYLON {
-    export class BaseTexture {
-        public name: string;
-        public delayLoadState = Engine.DELAYLOADSTATE_NONE;
-        public hasAlpha = false;
-        public getAlphaFromRGB = false;
-        public level = 1;
-        public isCube = false;
-        public isRenderTarget = false;
-        public animations = new Array<Animation>();
-        public onDispose: () => void;
-        public coordinatesIndex = 0;
-        public coordinatesMode = Texture.EXPLICIT_MODE;
-        public wrapU = Texture.WRAP_ADDRESSMODE;
-        public wrapV = Texture.WRAP_ADDRESSMODE;
-        public anisotropicFilteringLevel = 4;
-        public _cachedAnisotropicFilteringLevel: number;
-
-        private _scene: Scene;
-        public _texture: WebGLTexture;
-
-        constructor(scene: Scene) {
-            this._scene = scene;
-            this._scene.textures.push(this);
-        }
-
-        public getScene(): Scene {
-            return this._scene;
-        }
-
-        public getTextureMatrix(): Matrix {
-            return null;
-        }
-
-        public getReflectionTextureMatrix(): Matrix {
-            return null;
-        }
-
-        public getInternalTexture(): WebGLTexture {
-            return this._texture;
-        }
-
-        public isReady(): boolean {
-            if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
-                return true;
-            }
-
-            if (this._texture) {
-                return this._texture.isReady;
-            }
-
-            return false;
-        }
-
-        public getSize(): ISize  {
-            if (this._texture._width) {
-                return { width: this._texture._width, height: this._texture._height };
-            }
-
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-
-            return { width: 0, height: 0 };
-        }
-
-        public getBaseSize(): ISize {
-            if (!this.isReady())
-                return { width: 0, height: 0 };
-
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-
-            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
-        }
-
-        public scale(ratio: number): void {
-        }
-
-        public get canRescale(): boolean {
-            return false;
-        }
-
-        public _removeFromCache(url: string, noMipmap: boolean): void {
-            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;
-                }
-            }
-        }
-
-        public _getFromCache(url: string, noMipmap: boolean, sampling?: number): WebGLTexture {
-            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;
-        }
-
-        public delayLoad(): void {
-        }        
-
-        public clone(): BaseTexture {
-            return null;
-        }
-
-        public releaseInternalTexture(): void {
-            if (this._texture) {
-                this._scene.getEngine().releaseInternalTexture(this._texture);
-                delete this._texture;
-            }
-        }
-
-        public dispose(): void {
-            // 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;
-            }
-
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            if (!this.name) {
-                return null;
-            }
-            
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.level = this.level;
-
-            serializationObject.coordinatesIndex = this.coordinatesIndex;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            serializationObject.wrapU = this.wrapU;
-            serializationObject.wrapV = this.wrapV;
-
-            // Animations
-            Animation.AppendSerializedAnimations(this, serializationObject);
-
-            return serializationObject;
-        }
-
-        public static ParseCubeTexture(parsedTexture: any, scene: Scene, rootUrl: string): CubeTexture {
-            var texture = null;
-            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        }
-
-        public static ParseTexture(parsedTexture: any, scene: Scene, rootUrl: string): BaseTexture {
-            if (parsedTexture.isCube) {
-                return BaseTexture.ParseCubeTexture(parsedTexture, scene, rootUrl);
-            }
-
-            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
-                return null;
-            }
-
-            var texture;
-
-            if (parsedTexture.mirrorPlane) {
-                texture = new MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-                texture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane);
-            } else if (parsedTexture.isRenderTarget) {
-                texture = new RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-            } else {
-                if (parsedTexture.base64String) {
-                    texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
-                } else {
-                    texture = new Texture(rootUrl + parsedTexture.name, scene);
-                }
-            }
-
-            texture.name = parsedTexture.name;
-            texture.hasAlpha = parsedTexture.hasAlpha;
-            texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
-            texture.level = parsedTexture.level;
-
-            texture.coordinatesIndex = parsedTexture.coordinatesIndex;
-            texture.coordinatesMode = parsedTexture.coordinatesMode;
-            texture.uOffset = parsedTexture.uOffset;
-            texture.vOffset = parsedTexture.vOffset;
-            texture.uScale = parsedTexture.uScale;
-            texture.vScale = parsedTexture.vScale;
-            texture.uAng = parsedTexture.uAng;
-            texture.vAng = parsedTexture.vAng;
-            texture.wAng = parsedTexture.wAng;
-
-            texture.wrapU = parsedTexture.wrapU;
-            texture.wrapV = parsedTexture.wrapV;
-
-            // Animations
-            if (parsedTexture.animations) {
-                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedTexture.animations[animationIndex];
-
-                    texture.animations.push(Animation.ParseAnimation(parsedAnimation));
-                }
-            }
-
-            return texture;
-        }
-    }
+module BABYLON {
+    export class BaseTexture {
+        public name: string;
+        public delayLoadState = Engine.DELAYLOADSTATE_NONE;
+        public hasAlpha = false;
+        public getAlphaFromRGB = false;
+        public level = 1;
+        public isCube = false;
+        public isRenderTarget = false;
+        public animations = new Array<Animation>();
+        public onDispose: () => void;
+        public coordinatesIndex = 0;
+        public coordinatesMode = Texture.EXPLICIT_MODE;
+        public wrapU = Texture.WRAP_ADDRESSMODE;
+        public wrapV = Texture.WRAP_ADDRESSMODE;
+        public anisotropicFilteringLevel = 4;
+        public _cachedAnisotropicFilteringLevel: number;
+
+        private _scene: Scene;
+        public _texture: WebGLTexture;
+
+        constructor(scene: Scene) {
+            this._scene = scene;
+            this._scene.textures.push(this);
+        }
+
+        public getScene(): Scene {
+            return this._scene;
+        }
+
+        public getTextureMatrix(): Matrix {
+            return null;
+        }
+
+        public getReflectionTextureMatrix(): Matrix {
+            return null;
+        }
+
+        public getInternalTexture(): WebGLTexture {
+            return this._texture;
+        }
+
+        public isReady(): boolean {
+            if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
+                return true;
+            }
+
+            if (this._texture) {
+                return this._texture.isReady;
+            }
+
+            return false;
+        }
+
+        public getSize(): ISize  {
+            if (this._texture._width) {
+                return { width: this._texture._width, height: this._texture._height };
+            }
+
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+
+            return { width: 0, height: 0 };
+        }
+
+        public getBaseSize(): ISize {
+            if (!this.isReady())
+                return { width: 0, height: 0 };
+
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+
+            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
+        }
+
+        public scale(ratio: number): void {
+        }
+
+        public get canRescale(): boolean {
+            return false;
+        }
+
+        public _removeFromCache(url: string, noMipmap: boolean): void {
+            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;
+                }
+            }
+        }
+
+        public _getFromCache(url: string, noMipmap: boolean, sampling?: number): WebGLTexture {
+            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;
+        }
+
+        public delayLoad(): void {
+        }        
+
+        public clone(): BaseTexture {
+            return null;
+        }
+
+        public releaseInternalTexture(): void {
+            if (this._texture) {
+                this._scene.getEngine().releaseInternalTexture(this._texture);
+                delete this._texture;
+            }
+        }
+
+        public dispose(): void {
+            // 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;
+            }
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            if (!this.name) {
+                return null;
+            }
+            
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.level = this.level;
+
+            serializationObject.coordinatesIndex = this.coordinatesIndex;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            serializationObject.wrapU = this.wrapU;
+            serializationObject.wrapV = this.wrapV;
+
+            // Animations
+            Animation.AppendSerializedAnimations(this, serializationObject);
+
+            return serializationObject;
+        }      
+    }
 } 

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

@@ -57,7 +57,7 @@ var BABYLON;
         CubeTexture.prototype.getReflectionTextureMatrix = function () {
             return this._textureMatrix;
         };
-        CubeTexture.ParseCubeTexture = function (parsedTexture, scene, rootUrl) {
+        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
             var texture = null;
             if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
                 texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);

+ 100 - 100
src/Materials/Textures/babylon.cubeTexture.ts

@@ -1,101 +1,101 @@
-module BABYLON {
-    export class CubeTexture extends BaseTexture {
-        public url: string;
-        public coordinatesMode = Texture.CUBIC_MODE;
-
-        private _noMipmap: boolean;
-        private _extensions: string[];
-        private _textureMatrix: Matrix;
-
-        constructor(rootUrl: string, scene: Scene, extensions?: string[], noMipmap?: boolean) {
-            super(scene);
-
-            this.name = rootUrl;
-            this.url = rootUrl;
-            this._noMipmap = noMipmap;
-            this.hasAlpha = false;
-
-            if (!rootUrl) {
-                return;
-            }
-
-            this._texture = this._getFromCache(rootUrl, noMipmap);
-
-            if (!extensions) {
-                extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
-            }
-
-            this._extensions = extensions;
-
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
-                } else {
-                    this.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-
-            this.isCube = true;
-
-            this._textureMatrix = Matrix.Identity();
-        }
-
-        public clone(): CubeTexture {
-            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
-
-            // 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
-        public delayLoad(): void {
-            if (this.delayLoadState !== Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-
-            this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
-            }
-        }
-
-        public getReflectionTextureMatrix(): Matrix {
-            return this._textureMatrix;
-        }
-        
-        public static ParseCubeTexture(parsedTexture: any, scene: Scene, rootUrl: string): CubeTexture {
-            var texture = null;
-            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        }
-
-        public serialize(): any {
-            if (!this.name) {
-                return null;
-            }
-
-            var serializationObject: any = {};
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.isCube = true;
-            serializationObject.level = this.level;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-
-            return serializationObject;
-        }
-    }
+module BABYLON {
+    export class CubeTexture extends BaseTexture {
+        public url: string;
+        public coordinatesMode = Texture.CUBIC_MODE;
+
+        private _noMipmap: boolean;
+        private _extensions: string[];
+        private _textureMatrix: Matrix;
+
+        constructor(rootUrl: string, scene: Scene, extensions?: string[], noMipmap?: boolean) {
+            super(scene);
+
+            this.name = rootUrl;
+            this.url = rootUrl;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+
+            if (!rootUrl) {
+                return;
+            }
+
+            this._texture = this._getFromCache(rootUrl, noMipmap);
+
+            if (!extensions) {
+                extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
+            }
+
+            this._extensions = extensions;
+
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
+                } else {
+                    this.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+
+            this.isCube = true;
+
+            this._textureMatrix = Matrix.Identity();
+        }
+
+        public clone(): CubeTexture {
+            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
+
+            // 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
+        public delayLoad(): void {
+            if (this.delayLoadState !== Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+
+            this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
+            }
+        }
+
+        public getReflectionTextureMatrix(): Matrix {
+            return this._textureMatrix;
+        }
+        
+        public static Parse(parsedTexture: any, scene: Scene, rootUrl: string): CubeTexture {
+            var texture = null;
+            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
+                texture.name = parsedTexture.name;
+                texture.hasAlpha = parsedTexture.hasAlpha;
+                texture.level = parsedTexture.level;
+                texture.coordinatesMode = parsedTexture.coordinatesMode;
+            }
+            return texture;
+        }
+
+        public serialize(): any {
+            if (!this.name) {
+                return null;
+            }
+
+            var serializationObject: any = {};
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.isCube = true;
+            serializationObject.level = this.level;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+
+            return serializationObject;
+        }
+    }
 } 

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

@@ -201,9 +201,9 @@ var BABYLON;
             if (onError === void 0) { onError = null; }
             return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
         };
-        Texture.ParseTexture = function (parsedTexture, scene, rootUrl) {
+        Texture.Parse = function (parsedTexture, scene, rootUrl) {
             if (parsedTexture.isCube) {
-                return BABYLON.CubeTexture.ParseCubeTexture(parsedTexture, scene, rootUrl);
+                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
             }
             if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
                 return null;
@@ -245,7 +245,7 @@ var BABYLON;
             if (parsedTexture.animations) {
                 for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
                     var parsedAnimation = parsedTexture.animations[animationIndex];
-                    texture.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
+                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                 }
             }
             return texture;

+ 318 - 318
src/Materials/Textures/babylon.texture.ts

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

+ 16 - 5
src/Materials/babylon.material.js

@@ -241,14 +241,25 @@ var BABYLON;
             serializationObject.backFaceCulling = this.backFaceCulling;
             return serializationObject;
         };
-        Material.ParseMaterial = function (parsedMaterial, scene, rootUrl) {
+        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
+            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
+            multiMaterial.id = parsedMultiMaterial.id;
+            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
+            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
+                var subMatId = parsedMultiMaterial.materials[matIndex];
+                if (subMatId) {
+                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
+                }
+                else {
+                    multiMaterial.subMaterials.push(null);
+                }
+            }
+            return multiMaterial;
+        };
+        Material.Parse = function (parsedMaterial, scene, rootUrl) {
             if (!parsedMaterial.customType) {
                 return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
             }
-            // parse Lava material
-            //else if (parsedMaterial.customType === "lava") {
-            //    return LavaMaterial.Parse(parsedMaterial, scene, rootUrl);
-            //}
             //TODO this is where custom materials are inspected and parsed.
             return null;
         };

+ 311 - 295
src/Materials/babylon.material.ts

@@ -1,296 +1,312 @@
-module BABYLON {
-    export class MaterialDefines {
-        _keys: string[];
-
-        public isEqual(other: MaterialDefines): boolean {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-
-                if (this[prop] !== other[prop]) {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        public cloneTo(other: MaterialDefines): void {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-
-                other[prop] = this[prop];
-            }
-        }
-
-        public reset(): void {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-
-                if (typeof (this[prop]) === "number") {
-                    this[prop] = 0;
-
-                } else {
-                    this[prop] = false;
-                }
-            }
-        }
-
-        public toString(): string {
-            var result = "";
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-
-                if (typeof (this[prop]) === "number") {
-                    result += "#define " + prop + " " + this[prop] + "\n";
-
-                } else if (this[prop]) {
-                    result += "#define " + prop + "\n";
-                }
-            }
-
-            return result;
-        }
-    }
-
-    export class Material {
-        private static _TriangleFillMode = 0;
-        private static _WireFrameFillMode = 1;
-        private static _PointFillMode = 2;
-
-        public static get TriangleFillMode(): number {
-            return Material._TriangleFillMode;
-        }
-
-        public static get WireFrameFillMode(): number {
-            return Material._WireFrameFillMode;
-        }
-
-        public static get PointFillMode(): number {
-            return Material._PointFillMode;
-        }
-
-        private static _ClockWiseSideOrientation = 0;
-        private static _CounterClockWiseSideOrientation = 1;
-
-        public static get ClockWiseSideOrientation(): number {
-            return Material._ClockWiseSideOrientation;
-        }
-
-        public static get CounterClockWiseSideOrientation(): number {
-            return Material._CounterClockWiseSideOrientation;
-        }
-
-        public id: string;
-        public checkReadyOnEveryCall = false;
-        public checkReadyOnlyOnce = false;
-        public state = "";
-        public alpha = 1.0;
-        public backFaceCulling = true;
-        public sideOrientation = Material.CounterClockWiseSideOrientation;
-        public onCompiled: (effect: Effect) => void;
-        public onError: (effect: Effect, errors: string) => void;
-        public onDispose: () => void;
-        public onBind: (material: Material, mesh: Mesh) => void;
-        public getRenderTargetTextures: () => SmartArray<RenderTargetTexture>;
-        public alphaMode = Engine.ALPHA_COMBINE;
-        public disableDepthWrite = false;
-        public fogEnabled = true;
-
-        public _effect: Effect;
-        public _wasPreviouslyReady = false;
-        private _scene: Scene;
-        private _fillMode = Material.TriangleFillMode;
-        private _cachedDepthWriteState: boolean;
-
-        public pointSize = 1.0;
-
-        public zOffset = 0;
-
-        public get wireframe(): boolean {
-            return this._fillMode === Material.WireFrameFillMode;
-        }
-
-        public set wireframe(value: boolean) {
-            this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
-        }
-
-        public get pointsCloud(): boolean {
-            return this._fillMode === Material.PointFillMode;
-        }
-
-        public set pointsCloud(value: boolean) {
-            this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
-        }
-
-        public get fillMode(): number {
-            return this._fillMode;
-        }
-
-        public set fillMode(value: number) {
-            this._fillMode = value;
-        }
-
-        constructor(public name: string, scene: Scene, doNotAdd?: boolean) {
-            this.id = name;
-
-            this._scene = scene;
-
-            if (!doNotAdd) {
-                scene.materials.push(this);
-            }
-        }
-
-        public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
-            return true;
-        }
-
-        public getEffect(): Effect {
-            return this._effect;
-        }
-
-        public getScene(): Scene {
-            return this._scene;
-        }
-
-        public needAlphaBlending(): boolean {
-            return (this.alpha < 1.0);
-        }
-
-        public needAlphaTesting(): boolean {
-            return false;
-        }
-
-        public getAlphaTestTexture(): BaseTexture {
-            return null;
-        }
-
-        public trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void) {
-        }
-
-        public markDirty(): void {
-            this._wasPreviouslyReady = false;
-        }
-
-        public _preBind(): void {
-            var engine = this._scene.getEngine();
-
-            engine.enableEffect(this._effect);
-            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
-        }
-
-        public bind(world: Matrix, mesh?: Mesh): void {
-            this._scene._cachedMaterial = this;
-
-            if (this.onBind) {
-                this.onBind(this, mesh);
-            }
-
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                this._cachedDepthWriteState = engine.getDepthWrite();
-                engine.setDepthWrite(false);
-            }
-        }
-
-        public bindOnlyWorldMatrix(world: Matrix): void {
-        }
-
-        public unbind(): void {
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                engine.setDepthWrite(this._cachedDepthWriteState);
-            }
-        }
-
-        public clone(name: string): Material {
-            return null;
-        }
-
-        public getBindedMeshes(): AbstractMesh[] {
-            var result = new Array<AbstractMesh>();
-
-            for (var index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-
-                if (mesh.material === this) {
-                    result.push(mesh);
-                }
-            }
-
-            return result;
-        }
-
-        public dispose(forceDisposeEffect?: boolean): void {
-            // Animations
-            this.getScene().stopAnimation(this);
-
-            // Remove from scene
-            var index = this._scene.materials.indexOf(this);
-            if (index >= 0) {
-                this._scene.materials.splice(index, 1);
-            }
-
-            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
-            if (forceDisposeEffect && this._effect) {
-                this._scene.getEngine()._releaseEffect(this._effect);
-                this._effect = null;
-            }
-
-            // Remove from meshes
-            for (index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-
-                if (mesh.material === this) {
-                    mesh.material = null;
-                }
-            }
-
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        }
-
-        public copyTo(other: Material): void {
-            other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
-            other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
-            other.alpha = this.alpha;
-            other.fillMode = this.fillMode;
-            other.backFaceCulling = this.backFaceCulling;
-            other.fogEnabled = this.fogEnabled;
-            other.wireframe = this.wireframe;
-            other.zOffset = this.zOffset;
-            other.alphaMode = this.alphaMode;
-            other.sideOrientation = this.sideOrientation;
-            other.disableDepthWrite = this.disableDepthWrite;
-            other.pointSize = this.pointSize;
-            other.pointsCloud = this.pointsCloud;
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            serializationObject.name = this.name;
-            serializationObject.alpha = this.alpha;
-
-            serializationObject.id = this.id;
-            serializationObject.tags = Tags.GetTags(this);
-            serializationObject.backFaceCulling = this.backFaceCulling;
-
-            return serializationObject;
-        }
-
-        public static ParseMaterial(parsedMaterial: any, scene: Scene, rootUrl: string) {
-            if (!parsedMaterial.customType) {
-                return StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
-            }
-            // parse Lava material
-            //else if (parsedMaterial.customType === "lava") {
-            //    return LavaMaterial.Parse(parsedMaterial, scene, rootUrl);
-            //}
-
-            //TODO this is where custom materials are inspected and parsed.
-            return null;
-        }
-    }
+module BABYLON {
+    export class MaterialDefines {
+        _keys: string[];
+
+        public isEqual(other: MaterialDefines): boolean {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+
+                if (this[prop] !== other[prop]) {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
+        public cloneTo(other: MaterialDefines): void {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+
+                other[prop] = this[prop];
+            }
+        }
+
+        public reset(): void {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+
+                if (typeof (this[prop]) === "number") {
+                    this[prop] = 0;
+
+                } else {
+                    this[prop] = false;
+                }
+            }
+        }
+
+        public toString(): string {
+            var result = "";
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+
+                if (typeof (this[prop]) === "number") {
+                    result += "#define " + prop + " " + this[prop] + "\n";
+
+                } else if (this[prop]) {
+                    result += "#define " + prop + "\n";
+                }
+            }
+
+            return result;
+        }
+    }
+
+    export class Material {
+        private static _TriangleFillMode = 0;
+        private static _WireFrameFillMode = 1;
+        private static _PointFillMode = 2;
+
+        public static get TriangleFillMode(): number {
+            return Material._TriangleFillMode;
+        }
+
+        public static get WireFrameFillMode(): number {
+            return Material._WireFrameFillMode;
+        }
+
+        public static get PointFillMode(): number {
+            return Material._PointFillMode;
+        }
+
+        private static _ClockWiseSideOrientation = 0;
+        private static _CounterClockWiseSideOrientation = 1;
+
+        public static get ClockWiseSideOrientation(): number {
+            return Material._ClockWiseSideOrientation;
+        }
+
+        public static get CounterClockWiseSideOrientation(): number {
+            return Material._CounterClockWiseSideOrientation;
+        }
+
+        public id: string;
+        public checkReadyOnEveryCall = false;
+        public checkReadyOnlyOnce = false;
+        public state = "";
+        public alpha = 1.0;
+        public backFaceCulling = true;
+        public sideOrientation = Material.CounterClockWiseSideOrientation;
+        public onCompiled: (effect: Effect) => void;
+        public onError: (effect: Effect, errors: string) => void;
+        public onDispose: () => void;
+        public onBind: (material: Material, mesh: Mesh) => void;
+        public getRenderTargetTextures: () => SmartArray<RenderTargetTexture>;
+        public alphaMode = Engine.ALPHA_COMBINE;
+        public disableDepthWrite = false;
+        public fogEnabled = true;
+
+        public _effect: Effect;
+        public _wasPreviouslyReady = false;
+        private _scene: Scene;
+        private _fillMode = Material.TriangleFillMode;
+        private _cachedDepthWriteState: boolean;
+
+        public pointSize = 1.0;
+
+        public zOffset = 0;
+
+        public get wireframe(): boolean {
+            return this._fillMode === Material.WireFrameFillMode;
+        }
+
+        public set wireframe(value: boolean) {
+            this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
+        }
+
+        public get pointsCloud(): boolean {
+            return this._fillMode === Material.PointFillMode;
+        }
+
+        public set pointsCloud(value: boolean) {
+            this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
+        }
+
+        public get fillMode(): number {
+            return this._fillMode;
+        }
+
+        public set fillMode(value: number) {
+            this._fillMode = value;
+        }
+
+        constructor(public name: string, scene: Scene, doNotAdd?: boolean) {
+            this.id = name;
+
+            this._scene = scene;
+
+            if (!doNotAdd) {
+                scene.materials.push(this);
+            }
+        }
+
+        public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
+            return true;
+        }
+
+        public getEffect(): Effect {
+            return this._effect;
+        }
+
+        public getScene(): Scene {
+            return this._scene;
+        }
+
+        public needAlphaBlending(): boolean {
+            return (this.alpha < 1.0);
+        }
+
+        public needAlphaTesting(): boolean {
+            return false;
+        }
+
+        public getAlphaTestTexture(): BaseTexture {
+            return null;
+        }
+
+        public trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void) {
+        }
+
+        public markDirty(): void {
+            this._wasPreviouslyReady = false;
+        }
+
+        public _preBind(): void {
+            var engine = this._scene.getEngine();
+
+            engine.enableEffect(this._effect);
+            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
+        }
+
+        public bind(world: Matrix, mesh?: Mesh): void {
+            this._scene._cachedMaterial = this;
+
+            if (this.onBind) {
+                this.onBind(this, mesh);
+            }
+
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                this._cachedDepthWriteState = engine.getDepthWrite();
+                engine.setDepthWrite(false);
+            }
+        }
+
+        public bindOnlyWorldMatrix(world: Matrix): void {
+        }
+
+        public unbind(): void {
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                engine.setDepthWrite(this._cachedDepthWriteState);
+            }
+        }
+
+        public clone(name: string): Material {
+            return null;
+        }
+
+        public getBindedMeshes(): AbstractMesh[] {
+            var result = new Array<AbstractMesh>();
+
+            for (var index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+
+                if (mesh.material === this) {
+                    result.push(mesh);
+                }
+            }
+
+            return result;
+        }
+
+        public dispose(forceDisposeEffect?: boolean): void {
+            // Animations
+            this.getScene().stopAnimation(this);
+
+            // Remove from scene
+            var index = this._scene.materials.indexOf(this);
+            if (index >= 0) {
+                this._scene.materials.splice(index, 1);
+            }
+
+            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
+            if (forceDisposeEffect && this._effect) {
+                this._scene.getEngine()._releaseEffect(this._effect);
+                this._effect = null;
+            }
+
+            // Remove from meshes
+            for (index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+
+                if (mesh.material === this) {
+                    mesh.material = null;
+                }
+            }
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+
+        public copyTo(other: Material): void {
+            other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
+            other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
+            other.alpha = this.alpha;
+            other.fillMode = this.fillMode;
+            other.backFaceCulling = this.backFaceCulling;
+            other.fogEnabled = this.fogEnabled;
+            other.wireframe = this.wireframe;
+            other.zOffset = this.zOffset;
+            other.alphaMode = this.alphaMode;
+            other.sideOrientation = this.sideOrientation;
+            other.disableDepthWrite = this.disableDepthWrite;
+            other.pointSize = this.pointSize;
+            other.pointsCloud = this.pointsCloud;
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            serializationObject.name = this.name;
+            serializationObject.alpha = this.alpha;
+
+            serializationObject.id = this.id;
+            serializationObject.tags = Tags.GetTags(this);
+            serializationObject.backFaceCulling = this.backFaceCulling;
+
+            return serializationObject;
+        }
+
+        public static ParseMultiMaterial(parsedMultiMaterial: any, scene: Scene): MultiMaterial {
+            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
+
+            multiMaterial.id = parsedMultiMaterial.id;
+
+            Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
+
+            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
+                var subMatId = parsedMultiMaterial.materials[matIndex];
+
+                if (subMatId) {
+                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
+                } else {
+                    multiMaterial.subMaterials.push(null);
+                }
+            }
+
+            return multiMaterial;
+        }
+
+        public static Parse(parsedMaterial: any, scene: Scene, rootUrl: string) {
+            if (!parsedMaterial.customType) {
+                return StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
+            }
+
+            //TODO this is where custom materials are inspected and parsed.
+            return null;
+        }
+    }
 } 

+ 0 - 15
src/Materials/babylon.multiMaterial.js

@@ -56,21 +56,6 @@ var BABYLON;
             }
             return serializationObject;
         };
-        MultiMaterial.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
-            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
-            multiMaterial.id = parsedMultiMaterial.id;
-            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
-            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
-                var subMatId = parsedMultiMaterial.materials[matIndex];
-                if (subMatId) {
-                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
-                }
-                else {
-                    multiMaterial.subMaterials.push(null);
-                }
-            }
-            return multiMaterial;
-        };
         return MultiMaterial;
     })(BABYLON.Material);
     BABYLON.MultiMaterial = MultiMaterial;

+ 67 - 86
src/Materials/babylon.multiMaterial.ts

@@ -1,87 +1,68 @@
-module BABYLON {
-    export class MultiMaterial extends Material {
-        public subMaterials = new Array<Material>();
-
-        constructor(name: string, scene: Scene) {
-            super(name, scene, true);
-
-            scene.multiMaterials.push(this);
-        }
-
-        // Properties
-        public getSubMaterial(index) {
-            if (index < 0 || index >= this.subMaterials.length) {
-                return this.getScene().defaultMaterial;
-            }
-
-            return this.subMaterials[index];
-        }
-
-        // Methods
-        public isReady(mesh?: AbstractMesh): boolean {
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = this.subMaterials[index];
-                if (subMaterial) {
-                    if (!this.subMaterials[index].isReady(mesh)) {
-                        return false;
-                    }
-                }
-            }
-
-            return true;
-        }
-
-        public clone(name: string): MultiMaterial {
-            var newMultiMaterial = new MultiMaterial(name, this.getScene());
-
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = this.subMaterials[index];
-                newMultiMaterial.subMaterials.push(subMaterial);
-            }
-
-            return newMultiMaterial;
-        }
-
-        public serialize(): any {
-            var serializationObject: any = {};
-
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.tags = Tags.GetTags(this);
-
-            serializationObject.materials = [];
-
-            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
-                var subMat = this.subMaterials[matIndex];
-
-                if (subMat) {
-                    serializationObject.materials.push(subMat.id);
-                } else {
-                    serializationObject.materials.push(null);
-                }
-            }
-
-            return serializationObject;
-        }
-
-        public static ParseMultiMaterial(parsedMultiMaterial: any, scene: Scene): MultiMaterial {
-            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
-
-            multiMaterial.id = parsedMultiMaterial.id;
-
-            Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
-
-            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
-                var subMatId = parsedMultiMaterial.materials[matIndex];
-
-                if (subMatId) {
-                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
-                } else {
-                    multiMaterial.subMaterials.push(null);
-                }
-            }
-
-            return multiMaterial;
-        }
-    }
+module BABYLON {
+    export class MultiMaterial extends Material {
+        public subMaterials = new Array<Material>();
+
+        constructor(name: string, scene: Scene) {
+            super(name, scene, true);
+
+            scene.multiMaterials.push(this);
+        }
+
+        // Properties
+        public getSubMaterial(index) {
+            if (index < 0 || index >= this.subMaterials.length) {
+                return this.getScene().defaultMaterial;
+            }
+
+            return this.subMaterials[index];
+        }
+
+        // Methods
+        public isReady(mesh?: AbstractMesh): boolean {
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = this.subMaterials[index];
+                if (subMaterial) {
+                    if (!this.subMaterials[index].isReady(mesh)) {
+                        return false;
+                    }
+                }
+            }
+
+            return true;
+        }
+
+        public clone(name: string): MultiMaterial {
+            var newMultiMaterial = new MultiMaterial(name, this.getScene());
+
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = this.subMaterials[index];
+                newMultiMaterial.subMaterials.push(subMaterial);
+            }
+
+            return newMultiMaterial;
+        }
+
+        public serialize(): any {
+            var serializationObject: any = {};
+
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.tags = Tags.GetTags(this);
+
+            serializationObject.materials = [];
+
+            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
+                var subMat = this.subMaterials[matIndex];
+
+                if (subMat) {
+                    serializationObject.materials.push(subMat.id);
+                } else {
+                    serializationObject.materials.push(null);
+                }
+            }
+
+            return serializationObject;
+        }
+
+    }
 } 

+ 21 - 21
src/Materials/babylon.standardMaterial.js

@@ -28,6 +28,15 @@ var BABYLON;
             serializationObject.power = this.power;
             return serializationObject;
         };
+        FresnelParameters.Parse = function (parsedFresnelParameters) {
+            var fresnelParameters = new FresnelParameters();
+            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
+            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
+            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
+            fresnelParameters.bias = parsedFresnelParameters.bias;
+            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
+            return fresnelParameters;
+        };
         return FresnelParameters;
     })();
     BABYLON.FresnelParameters = FresnelParameters;
@@ -925,15 +934,6 @@ var BABYLON;
             }
             return serializationObject;
         };
-        StandardMaterial.ParseFresnelParameters = function (parsedFresnelParameters) {
-            var fresnelParameters = new FresnelParameters();
-            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
-            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
-            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
-            fresnelParameters.bias = parsedFresnelParameters.bias;
-            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
-            return fresnelParameters;
-        };
         StandardMaterial.Parse = function (source, scene, rootUrl) {
             var material = new StandardMaterial(source.name, scene);
             material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
@@ -952,41 +952,41 @@ var BABYLON;
             material.backFaceCulling = source.backFaceCulling;
             material.wireframe = source.wireframe;
             if (source.diffuseTexture) {
-                material.diffuseTexture = BABYLON.Texture.ParseTexture(source.diffuseTexture, scene, rootUrl);
+                material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
             }
             if (source.diffuseFresnelParameters) {
-                material.diffuseFresnelParameters = StandardMaterial.ParseFresnelParameters(source.diffuseFresnelParameters);
+                material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
             }
             if (source.ambientTexture) {
-                material.ambientTexture = BABYLON.Texture.ParseTexture(source.ambientTexture, scene, rootUrl);
+                material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
             }
             if (source.opacityTexture) {
-                material.opacityTexture = BABYLON.Texture.ParseTexture(source.opacityTexture, scene, rootUrl);
+                material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
             }
             if (source.opacityFresnelParameters) {
-                material.opacityFresnelParameters = StandardMaterial.ParseFresnelParameters(source.opacityFresnelParameters);
+                material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
             }
             if (source.reflectionTexture) {
-                material.reflectionTexture = BABYLON.Texture.ParseTexture(source.reflectionTexture, scene, rootUrl);
+                material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
             }
             if (source.reflectionFresnelParameters) {
-                material.reflectionFresnelParameters = StandardMaterial.ParseFresnelParameters(source.reflectionFresnelParameters);
+                material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
             }
             if (source.emissiveTexture) {
-                material.emissiveTexture = BABYLON.Texture.ParseTexture(source.emissiveTexture, scene, rootUrl);
+                material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
             }
             if (source.lightmapTexture) {
-                material.lightmapTexture = BABYLON.Texture.ParseTexture(source.lightmapTexture, scene, rootUrl);
+                material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
                 material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
             }
             if (source.emissiveFresnelParameters) {
-                material.emissiveFresnelParameters = StandardMaterial.ParseFresnelParameters(source.emissiveFresnelParameters);
+                material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
             }
             if (source.specularTexture) {
-                material.specularTexture = BABYLON.Texture.ParseTexture(source.specularTexture, scene, rootUrl);
+                material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
             }
             if (source.bumpTexture) {
-                material.bumpTexture = BABYLON.Texture.ParseTexture(source.bumpTexture, scene, rootUrl);
+                material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
             }
             if (source.checkReadyOnlyOnce) {
                 material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1225 - 1225
src/Materials/babylon.standardMaterial.ts


+ 109 - 8
src/Mesh/babylon.geometry.js

@@ -378,6 +378,53 @@ var BABYLON;
             geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
             return geometry;
         };
+        Geometry.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.id = this.id;
+            if (BABYLON.Tags.HasTags(this)) {
+                serializationObject.tags = BABYLON.Tags.GetTags(this);
+            }
+            return serializationObject;
+        };
+        Geometry.prototype.serializeVerticeData = function () {
+            var serializationObject = this.serialize();
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
+                serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
+                serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
+                serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
+                serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
+                serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
+                serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
+                serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
+                serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
+                serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
+                serializationObject.matricesIndices._isExpanded = true;
+            }
+            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
+            }
+            serializationObject.indices = this.getIndices();
+            return serializationObject;
+        };
         // Statics
         Geometry.ExtractFromMesh = function (mesh, id) {
             var geometry = mesh._geometry;
@@ -553,7 +600,7 @@ var BABYLON;
                 scene['_selectionOctree'].addMesh(mesh);
             }
         };
-        Geometry.ParseGeometry = function (parsedVertexData, scene, rootUrl) {
+        Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
             if (scene.getGeometryByID(parsedVertexData.id)) {
                 return null; // null since geometry could be something else than a box...
             }
@@ -651,6 +698,11 @@ var BABYLON;
                 _Primitive.prototype.copy = function (id) {
                     throw new Error("Must be overriden in sub-classes.");
                 };
+                _Primitive.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.canBeRegenerated = this.canBeRegenerated();
+                    return serializationObject;
+                };
                 return _Primitive;
             })(Geometry);
             Primitives._Primitive = _Primitive;
@@ -688,7 +740,12 @@ var BABYLON;
                 Box.prototype.copy = function (id) {
                     return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
                 };
-                Box.ParseBox = function (parsedBox, scene) {
+                Box.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.size = this.size;
+                    return serializationObject;
+                };
+                Box.Parse = function (parsedBox, scene) {
                     if (scene.getGeometryByID(parsedBox.id)) {
                         return null; // null since geometry could be something else than a box...
                     }
@@ -715,7 +772,13 @@ var BABYLON;
                 Sphere.prototype.copy = function (id) {
                     return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
                 };
-                Sphere.ParseSphere = function (parsedSphere, scene) {
+                Sphere.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.segments = this.segments;
+                    serializationObject.diameter = this.diameter;
+                    return serializationObject;
+                };
+                Sphere.Parse = function (parsedSphere, scene) {
                     if (scene.getGeometryByID(parsedSphere.id)) {
                         return null; // null since geometry could be something else than a sphere...
                     }
@@ -764,7 +827,15 @@ var BABYLON;
                 Cylinder.prototype.copy = function (id) {
                     return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
                 };
-                Cylinder.ParseCylinder = function (parsedCylinder, scene) {
+                Cylinder.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.height = this.height;
+                    serializationObject.diameterTop = this.diameterTop;
+                    serializationObject.diameterBottom = this.diameterBottom;
+                    serializationObject.tessellation = this.tessellation;
+                    return serializationObject;
+                };
+                Cylinder.Parse = function (parsedCylinder, scene) {
                     if (scene.getGeometryByID(parsedCylinder.id)) {
                         return null; // null since geometry could be something else than a cylinder...
                     }
@@ -792,7 +863,14 @@ var BABYLON;
                 Torus.prototype.copy = function (id) {
                     return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
                 };
-                Torus.ParseTorus = function (parsedTorus, scene) {
+                Torus.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.diameter = this.diameter;
+                    serializationObject.thickness = this.thickness;
+                    serializationObject.tessellation = this.tessellation;
+                    return serializationObject;
+                };
+                Torus.Parse = function (parsedTorus, scene) {
                     if (scene.getGeometryByID(parsedTorus.id)) {
                         return null; // null since geometry could be something else than a torus...
                     }
@@ -818,7 +896,14 @@ var BABYLON;
                 Ground.prototype.copy = function (id) {
                     return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
                 };
-                Ground.ParseGround = function (parsedGround, scene) {
+                Ground.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.width = this.width;
+                    serializationObject.height = this.height;
+                    serializationObject.subdivisions = this.subdivisions;
+                    return serializationObject;
+                };
+                Ground.Parse = function (parsedGround, scene) {
                     if (scene.getGeometryByID(parsedGround.id)) {
                         return null; // null since geometry could be something else than a ground...
                     }
@@ -864,7 +949,12 @@ var BABYLON;
                 Plane.prototype.copy = function (id) {
                     return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
                 };
-                Plane.ParsePlane = function (parsedPlane, scene) {
+                Plane.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.size = this.size;
+                    return serializationObject;
+                };
+                Plane.Parse = function (parsedPlane, scene) {
                     if (scene.getGeometryByID(parsedPlane.id)) {
                         return null; // null since geometry could be something else than a ground...
                     }
@@ -895,7 +985,18 @@ var BABYLON;
                 TorusKnot.prototype.copy = function (id) {
                     return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
                 };
-                TorusKnot.ParseTorusKnot = function (parsedTorusKnot, scene) {
+                TorusKnot.prototype.serialize = function () {
+                    var serializationObject = _super.prototype.serialize.call(this);
+                    serializationObject.radius = this.radius;
+                    serializationObject.tube = this.tube;
+                    serializationObject.radialSegments = this.radialSegments;
+                    serializationObject.tubularSegments = this.tubularSegments;
+                    serializationObject.p = this.p;
+                    serializationObject.q = this.q;
+                    return serializationObject;
+                };
+                ;
+                TorusKnot.Parse = function (parsedTorusKnot, scene) {
                     if (scene.getGeometryByID(parsedTorusKnot.id)) {
                         return null; // null since geometry could be something else than a ground...
                     }

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1298 - 1156
src/Mesh/babylon.geometry.ts


+ 3 - 3
src/Mesh/babylon.mesh.js

@@ -1059,7 +1059,7 @@ var BABYLON;
             });
         };
         // Statics
-        Mesh.ParseMesh = function (parsedMesh, scene, rootUrl) {
+        Mesh.Parse = function (parsedMesh, scene, rootUrl) {
             var mesh = new Mesh(parsedMesh.name, scene);
             mesh.id = parsedMesh.id;
             BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
@@ -1180,7 +1180,7 @@ var BABYLON;
             if (parsedMesh.animations) {
                 for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
                     var parsedAnimation = parsedMesh.animations[animationIndex];
-                    mesh.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
+                    mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                 }
             }
             if (parsedMesh.autoAnimate) {
@@ -1211,7 +1211,7 @@ var BABYLON;
                     if (parsedMesh.animations) {
                         for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
                             parsedAnimation = parsedMesh.animations[animationIndex];
-                            instance.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
+                            instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                         }
                     }
                 }

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1913 - 1913
src/Mesh/babylon.mesh.ts


+ 39 - 0
src/Mesh/babylon.mesh.vertexData.js

@@ -287,6 +287,45 @@ var BABYLON;
                 }
             }
         };
+        VertexData.prototype.serialize = function () {
+            var serializationObject = this.serialize();
+            if (this.positions) {
+                serializationObject.positions = this.positions;
+            }
+            if (this.normals) {
+                serializationObject.normals = this.normals;
+            }
+            if (this.uvs) {
+                serializationObject.uvs = this.uvs;
+            }
+            if (this.uvs2) {
+                serializationObject.uvs2 = this.uvs2;
+            }
+            if (this.uvs3) {
+                serializationObject.uvs3 = this.uvs3;
+            }
+            if (this.uvs4) {
+                serializationObject.uvs4 = this.uvs4;
+            }
+            if (this.uvs5) {
+                serializationObject.uvs5 = this.uvs5;
+            }
+            if (this.uvs6) {
+                serializationObject.uvs6 = this.uvs6;
+            }
+            if (this.colors) {
+                serializationObject.colors = this.colors;
+            }
+            if (this.matricesIndices) {
+                serializationObject.matricesIndices = this.matricesIndices;
+                serializationObject.matricesIndices._isExpanded = true;
+            }
+            if (this.matricesWeights) {
+                serializationObject.matricesWeights = this.matricesWeights;
+            }
+            serializationObject.indices = this.indices;
+            return serializationObject;
+        };
         // Statics
         VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
             return VertexData._ExtractFrom(mesh, copyWhenShared);

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 2233 - 2180
src/Mesh/babylon.mesh.vertexData.ts


+ 1 - 1
src/Particles/babylon.particleSystem.js

@@ -357,7 +357,7 @@ var BABYLON;
             serializationObject.blendMode = this.blendMode;
             return serializationObject;
         };
-        ParticleSystem.ParseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
+        ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
             var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
             var particleSystem = new ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
             if (parsedParticleSystem.textureName) {

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 515 - 515
src/Particles/babylon.particleSystem.ts


+ 8 - 116
src/Tools/babylon.sceneSerializer.js

@@ -1,147 +1,39 @@
 var BABYLON;
 (function (BABYLON) {
     var serializedGeometries = [];
-    var serializeVertexData;
-    var serializeTorusKnot;
-    var serializePlane;
-    var serializeGround;
-    var serializeTorus;
-    var serializeCylinder;
-    var serializeSphere;
-    var serializeBox;
     var serializeGeometry = function (geometry, serializationGeometries) {
         if (serializedGeometries[geometry.id]) {
             return;
         }
         if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
-            serializationGeometries.boxes.push(serializeBox(geometry));
+            serializationGeometries.boxes.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
-            serializationGeometries.spheres.push(serializeSphere(geometry));
+            serializationGeometries.spheres.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
-            serializationGeometries.cylinders.push(serializeCylinder(geometry));
+            serializationGeometries.cylinders.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
-            serializationGeometries.toruses.push(serializeTorus(geometry));
+            serializationGeometries.toruses.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
-            serializationGeometries.grounds.push(serializeGround(geometry));
+            serializationGeometries.grounds.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
-            serializationGeometries.planes.push(serializePlane(geometry));
+            serializationGeometries.planes.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
-            serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
+            serializationGeometries.torusKnots.push(geometry.serialize());
         }
         else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
             throw new Error("Unknown primitive type");
         }
         else {
-            serializationGeometries.vertexData.push(serializeVertexData(geometry));
+            serializationGeometries.vertexData.push(geometry.serializeVerticeData());
         }
         serializedGeometries[geometry.id] = true;
     };
-    var serializeGeometryBase = function (geometry) {
-        var serializationObject = {};
-        serializationObject.id = geometry.id;
-        if (BABYLON.Tags.HasTags(geometry)) {
-            serializationObject.tags = BABYLON.Tags.GetTags(geometry);
-        }
-        return serializationObject;
-    };
-    serializeVertexData = function (vertexData) {
-        var serializationObject = serializeGeometryBase(vertexData);
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
-            serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
-            serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
-            serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
-            serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
-            serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
-            serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
-            serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
-            serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
-            serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
-            serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
-            serializationObject.matricesIndices._isExpanded = true;
-        }
-        if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
-            serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
-        }
-        serializationObject.indices = vertexData.getIndices();
-        return serializationObject;
-    };
-    var serializePrimitive = function (primitive) {
-        var serializationObject = serializeGeometryBase(primitive);
-        serializationObject.canBeRegenerated = primitive.canBeRegenerated();
-        return serializationObject;
-    };
-    serializeBox = function (box) {
-        var serializationObject = serializePrimitive(box);
-        serializationObject.size = box.size;
-        return serializationObject;
-    };
-    serializeSphere = function (sphere) {
-        var serializationObject = serializePrimitive(sphere);
-        serializationObject.segments = sphere.segments;
-        serializationObject.diameter = sphere.diameter;
-        return serializationObject;
-    };
-    serializeCylinder = function (cylinder) {
-        var serializationObject = serializePrimitive(cylinder);
-        serializationObject.height = cylinder.height;
-        serializationObject.diameterTop = cylinder.diameterTop;
-        serializationObject.diameterBottom = cylinder.diameterBottom;
-        serializationObject.tessellation = cylinder.tessellation;
-        return serializationObject;
-    };
-    serializeTorus = function (torus) {
-        var serializationObject = serializePrimitive(torus);
-        serializationObject.diameter = torus.diameter;
-        serializationObject.thickness = torus.thickness;
-        serializationObject.tessellation = torus.tessellation;
-        return serializationObject;
-    };
-    serializeGround = function (ground) {
-        var serializationObject = serializePrimitive(ground);
-        serializationObject.width = ground.width;
-        serializationObject.height = ground.height;
-        serializationObject.subdivisions = ground.subdivisions;
-        return serializationObject;
-    };
-    serializePlane = function (plane) {
-        var serializationObject = serializePrimitive(plane);
-        serializationObject.size = plane.size;
-        return serializationObject;
-    };
-    serializeTorusKnot = function (torusKnot) {
-        var serializationObject = serializePrimitive(torusKnot);
-        serializationObject.radius = torusKnot.radius;
-        serializationObject.tube = torusKnot.tube;
-        serializationObject.radialSegments = torusKnot.radialSegments;
-        serializationObject.tubularSegments = torusKnot.tubularSegments;
-        serializationObject.p = torusKnot.p;
-        serializationObject.q = torusKnot.q;
-        return serializationObject;
-    };
     var serializeMesh = function (mesh, serializationScene) {
         var serializationObject = {};
         serializationObject.name = mesh.name;

+ 368 - 509
src/Tools/babylon.sceneSerializer.ts

@@ -1,510 +1,369 @@
-module BABYLON {  
-    var serializedGeometries: Geometry[] = [];
-    var serializeVertexData: (vertexData: Geometry) => any;
-    var serializeTorusKnot: (torusKnot: Geometry.Primitives.TorusKnot) => any;
-    var serializePlane: (plane) => any;
-    var serializeGround: (ground: Geometry.Primitives.Ground) => any;
-    var serializeTorus: (torus: Geometry.Primitives.Torus) => any;
-    var serializeCylinder: (cylinder: Geometry.Primitives.Cylinder) => any;
-    var serializeSphere: (sphere: Geometry.Primitives.Sphere) => any;
-    var serializeBox: (box: Geometry.Primitives.Box) => any;
-    var serializeGeometry = (geometry: Geometry, serializationGeometries: any): any => {
-        if (serializedGeometries[geometry.id]) {
-            return;
-        }
-        if (geometry instanceof Geometry.Primitives.Box) {
-            serializationGeometries.boxes.push(serializeBox(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.Sphere) {
-            serializationGeometries.spheres.push(serializeSphere(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.Cylinder) {
-            serializationGeometries.cylinders.push(serializeCylinder(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.Torus) {
-            serializationGeometries.toruses.push(serializeTorus(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.Ground) {
-            serializationGeometries.grounds.push(serializeGround(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.Plane) {
-            serializationGeometries.planes.push(serializePlane(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives.TorusKnot) {
-            serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
-        }
-        else if (geometry instanceof Geometry.Primitives._Primitive) {
-            throw new Error("Unknown primitive type");
-        }
-        else {
-            serializationGeometries.vertexData.push(serializeVertexData(geometry));
-        }
-
-        serializedGeometries[geometry.id] = true;
-    };
-
-    var serializeGeometryBase = (geometry: Geometry): any => {
-        var serializationObject: any = {};
-
-        serializationObject.id = geometry.id;
-
-        if (Tags.HasTags(geometry)) {
-            serializationObject.tags = Tags.GetTags(geometry);
-        }
-
-        return serializationObject;
-    };
-    serializeVertexData = (vertexData: Geometry): any => {
-        var serializationObject = serializeGeometryBase(vertexData);
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.PositionKind)) {
-            serializationObject.positions = vertexData.getVerticesData(VertexBuffer.PositionKind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.NormalKind)) {
-            serializationObject.normals = vertexData.getVerticesData(VertexBuffer.NormalKind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UVKind)) {
-            serializationObject.uvs = vertexData.getVerticesData(VertexBuffer.UVKind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
-            serializationObject.uvs2 = vertexData.getVerticesData(VertexBuffer.UV2Kind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
-            serializationObject.uvs3 = vertexData.getVerticesData(VertexBuffer.UV3Kind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
-            serializationObject.uvs4 = vertexData.getVerticesData(VertexBuffer.UV4Kind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
-            serializationObject.uvs5 = vertexData.getVerticesData(VertexBuffer.UV5Kind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
-            serializationObject.uvs6 = vertexData.getVerticesData(VertexBuffer.UV6Kind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.ColorKind)) {
-            serializationObject.colors = vertexData.getVerticesData(VertexBuffer.ColorKind);
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
-            serializationObject.matricesIndices = vertexData.getVerticesData(VertexBuffer.MatricesIndicesKind);
-            serializationObject.matricesIndices._isExpanded = true;
-        }
-
-        if (vertexData.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
-            serializationObject.matricesWeights = vertexData.getVerticesData(VertexBuffer.MatricesWeightsKind);
-        }
-
-        serializationObject.indices = vertexData.getIndices();
-
-        return serializationObject;
-    };
-    var serializePrimitive = (primitive: Geometry.Primitives._Primitive): any => {
-        var serializationObject = serializeGeometryBase(primitive);
-
-        serializationObject.canBeRegenerated = primitive.canBeRegenerated();
-
-        return serializationObject;
-    };
-    serializeBox = (box: Geometry.Primitives.Box): any => {
-        var serializationObject = serializePrimitive(box);
-
-        serializationObject.size = box.size;
-
-        return serializationObject;
-    };
-    serializeSphere = (sphere: Geometry.Primitives.Sphere): any => {
-        var serializationObject = serializePrimitive(sphere);
-
-        serializationObject.segments = sphere.segments;
-        serializationObject.diameter = sphere.diameter;
-
-        return serializationObject;
-    };
-    serializeCylinder = (cylinder: Geometry.Primitives.Cylinder): any => {
-        var serializationObject = serializePrimitive(cylinder);
-
-        serializationObject.height = cylinder.height;
-        serializationObject.diameterTop = cylinder.diameterTop;
-        serializationObject.diameterBottom = cylinder.diameterBottom;
-        serializationObject.tessellation = cylinder.tessellation;
-
-        return serializationObject;
-    };
-    serializeTorus = (torus: Geometry.Primitives.Torus): any => {
-        var serializationObject = serializePrimitive(torus);
-
-        serializationObject.diameter = torus.diameter;
-        serializationObject.thickness = torus.thickness;
-        serializationObject.tessellation = torus.tessellation;
-
-        return serializationObject;
-    };
-    serializeGround = (ground: Geometry.Primitives.Ground): any => {
-        var serializationObject = serializePrimitive(ground);
-
-        serializationObject.width = ground.width;
-        serializationObject.height = ground.height;
-        serializationObject.subdivisions = ground.subdivisions;
-
-        return serializationObject;
-    };
-    serializePlane = (plane: Geometry.Primitives.Plane): any => {
-        var serializationObject = serializePrimitive(plane);
-
-        serializationObject.size = plane.size;
-
-        return serializationObject;
-    };
-    serializeTorusKnot = (torusKnot: Geometry.Primitives.TorusKnot): any => {
-        var serializationObject = serializePrimitive(torusKnot);
-
-        serializationObject.radius = torusKnot.radius;
-        serializationObject.tube = torusKnot.tube;
-        serializationObject.radialSegments = torusKnot.radialSegments;
-        serializationObject.tubularSegments = torusKnot.tubularSegments;
-        serializationObject.p = torusKnot.p;
-        serializationObject.q = torusKnot.q;
-
-        return serializationObject;
-    };
-    var serializeMesh = (mesh: Mesh, serializationScene: any): any => {
-        var serializationObject: any = {};
-
-        serializationObject.name = mesh.name;
-        serializationObject.id = mesh.id;
-
-        if (Tags.HasTags(mesh)) {
-            serializationObject.tags = Tags.GetTags(mesh);
-        }
-
-        serializationObject.position = mesh.position.asArray();
-
-        if (mesh.rotationQuaternion) {
-            serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
-        } else if (mesh.rotation) {
-            serializationObject.rotation = mesh.rotation.asArray();
-        }
-
-        serializationObject.scaling = mesh.scaling.asArray();
-        serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
-
-        serializationObject.isEnabled = mesh.isEnabled();
-        serializationObject.isVisible = mesh.isVisible;
-        serializationObject.infiniteDistance = mesh.infiniteDistance;
-        serializationObject.pickable = mesh.isPickable;
-
-        serializationObject.receiveShadows = mesh.receiveShadows;
-
-        serializationObject.billboardMode = mesh.billboardMode;
-        serializationObject.visibility = mesh.visibility;
-
-        serializationObject.checkCollisions = mesh.checkCollisions;
-
-        // Parent
-        if (mesh.parent) {
-            serializationObject.parentId = mesh.parent.id;
-        }
-
-        // Geometry
-        var geometry = mesh._geometry;
-        if (geometry) {
-            var geometryId = geometry.id;
-            serializationObject.geometryId = geometryId;
-
-            if (!mesh.getScene().getGeometryByID(geometryId)) {
-                // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
-                serializeGeometry(geometry, serializationScene.geometries);
-            }
-
-            // SubMeshes
-            serializationObject.subMeshes = [];
-            for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                var subMesh = mesh.subMeshes[subIndex];
-
-                serializationObject.subMeshes.push({
-                    materialIndex: subMesh.materialIndex,
-                    verticesStart: subMesh.verticesStart,
-                    verticesCount: subMesh.verticesCount,
-                    indexStart: subMesh.indexStart,
-                    indexCount: subMesh.indexCount
-                });
-            }
-        }
-
-        // Material
-        if (mesh.material) {
-            serializationObject.materialId = mesh.material.id;
-        } else {
-            mesh.material = null;
-        }
-
-        // Skeleton
-        if (mesh.skeleton) {
-            serializationObject.skeletonId = mesh.skeleton.id;
-        }
-
-        // Physics
-        if (mesh.getPhysicsImpostor() !== PhysicsEngine.NoImpostor) {
-            serializationObject.physicsMass = mesh.getPhysicsMass();
-            serializationObject.physicsFriction = mesh.getPhysicsFriction();
-            serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
-
-            switch (mesh.getPhysicsImpostor()) {
-                case PhysicsEngine.BoxImpostor:
-                    serializationObject.physicsImpostor = 1;
-                    break;
-                case PhysicsEngine.SphereImpostor:
-                    serializationObject.physicsImpostor = 2;
-                    break;
-            }
-        }
-
-        // Instances
-        serializationObject.instances = [];
-        for (var index = 0; index < mesh.instances.length; index++) {
-            var instance = mesh.instances[index];
-            var serializationInstance = {
-                name: instance.name,
-                position: instance.position.asArray(),
-                rotation: instance.rotation.asArray(),
-                rotationQuaternion: instance.rotationQuaternion.asArray(),
-                scaling: instance.scaling.asArray()
-            };
-            serializationObject.instances.push(serializationInstance);
-
-            // Animations
-            Animation.AppendSerializedAnimations(instance, serializationInstance);
-        }
-
-        // Animations
-        Animation.AppendSerializedAnimations(mesh, serializationObject);
-
-        // Layer mask
-        serializationObject.layerMask = mesh.layerMask;
-
-        return serializationObject;
-    };
-
-    var finalizeSingleMesh = (mesh: Mesh, serializationObject: any) => {
-        //only works if the mesh is already loaded
-        if (mesh.delayLoadState === Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === Engine.DELAYLOADSTATE_NONE) {
-            //serialize material
-            if (mesh.material) {
-                if (mesh.material instanceof StandardMaterial) {
-                    serializationObject.materials = serializationObject.materials || [];
-                    if (!serializationObject.materials.some(mat => (mat.id === mesh.material.id))) {
-                        serializationObject.materials.push(mesh.material.serialize());
-                    }
-                } else if (mesh.material instanceof MultiMaterial) {
-                    serializationObject.multiMaterials = serializationObject.multiMaterials || [];
-                    if (!serializationObject.multiMaterials.some(mat => (mat.id === mesh.material.id))) {
-                        serializationObject.multiMaterials.push(mesh.material.serialize());
-                    }
-
-                }
-            }
-            //serialize geometry
-            var geometry = mesh._geometry;
-            if (geometry) {
-                if (!serializationObject.geometries) {
-                    serializationObject.geometries = {};
-
-                    serializationObject.geometries.boxes = [];
-                    serializationObject.geometries.spheres = [];
-                    serializationObject.geometries.cylinders = [];
-                    serializationObject.geometries.toruses = [];
-                    serializationObject.geometries.grounds = [];
-                    serializationObject.geometries.planes = [];
-                    serializationObject.geometries.torusKnots = [];
-                    serializationObject.geometries.vertexData = [];
-                }
-
-                serializeGeometry(geometry, serializationObject.geometries);
-            }
-            // Skeletons
-            if (mesh.skeleton) {
-                serializationObject.skeletons = serializationObject.skeletons || [];
-                serializationObject.skeletons.push(mesh.skeleton.serialize());
-            }
-
-            //serialize the actual mesh
-            serializationObject.meshes = serializationObject.meshes || [];
-            serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
-        }
-    }
-
-
-    export class SceneSerializer {
-        public static Serialize(scene: Scene): any {
-            var serializationObject: any = {};
-
-            // Scene
-            serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
-            serializationObject.autoClear = scene.autoClear;
-            serializationObject.clearColor = scene.clearColor.asArray();
-            serializationObject.ambientColor = scene.ambientColor.asArray();
-            serializationObject.gravity = scene.gravity.asArray();
-            serializationObject.collisionsEnabled = scene.collisionsEnabled;
-            serializationObject.workerCollisions = scene.workerCollisions;
-            
-            // Fog
-            if (scene.fogMode && scene.fogMode !== 0) {
-                serializationObject.fogMode = scene.fogMode;
-                serializationObject.fogColor = scene.fogColor.asArray();
-                serializationObject.fogStart = scene.fogStart;
-                serializationObject.fogEnd = scene.fogEnd;
-                serializationObject.fogDensity = scene.fogDensity;
-            }
-            
-            //Physics
-            if (scene.isPhysicsEnabled()) {
-                serializationObject.physicsEnabled = true;
-                serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
-                serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
-            }
-
-            // Lights
-            serializationObject.lights = [];
-            var index: number;
-            var light: Light;
-            for (index = 0; index < scene.lights.length; index++) {
-                light = scene.lights[index];
-                serializationObject.lights.push(light.serialize());
-            }
-
-            // Cameras
-            serializationObject.cameras = [];
-            for (index = 0; index < scene.cameras.length; index++) {
-                var camera = scene.cameras[index];
-                serializationObject.cameras.push(camera.serialize());
-            }
-
-            if (scene.activeCamera) {
-                serializationObject.activeCameraID = scene.activeCamera.id;
-            }
-
-            // Materials
-            serializationObject.materials = [];
-            serializationObject.multiMaterials = [];
-            var material: Material;
-            for (index = 0; index < scene.materials.length; index++) {
-                material = scene.materials[index];
-                serializationObject.materials.push(material.serialize());
-            }
-
-            // MultiMaterials
-            serializationObject.multiMaterials = [];
-            for (index = 0; index < scene.multiMaterials.length; index++) {
-                var multiMaterial = scene.multiMaterials[index];
-                serializationObject.multiMaterials.push(multiMaterial.serialize());
-            }
-
-            for (index = 0; index < scene.materials.length; index++) {
-                material = scene.materials[index];
-                serializationObject.materials.push(material.serialize());
-            }
-
-            // Skeletons
-            serializationObject.skeletons = [];
-            for (index = 0; index < scene.skeletons.length; index++) {
-                serializationObject.skeletons.push(scene.skeletons[index].serialize());
-            }
-
-            // Geometries
-            serializationObject.geometries = {};
-
-            serializationObject.geometries.boxes = [];
-            serializationObject.geometries.spheres = [];
-            serializationObject.geometries.cylinders = [];
-            serializationObject.geometries.toruses = [];
-            serializationObject.geometries.grounds = [];
-            serializationObject.geometries.planes = [];
-            serializationObject.geometries.torusKnots = [];
-            serializationObject.geometries.vertexData = [];
-
-            serializedGeometries = [];
-            var geometries = scene.getGeometries();
-            for (index = 0; index < geometries.length; index++) {
-                var geometry = geometries[index];
-
-                if (geometry.isReady()) {
-                    serializeGeometry(geometry, serializationObject.geometries);
-                }
-            }
-
-            // Meshes
-            serializationObject.meshes = [];
-            for (index = 0; index < scene.meshes.length; index++) {
-                var abstractMesh = scene.meshes[index];
-
-                if (abstractMesh instanceof Mesh) {
-                    var mesh = abstractMesh;
-                    if (mesh.delayLoadState === Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === Engine.DELAYLOADSTATE_NONE) {
-                        serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
-                    }
-                }
-            }
-
-            // Particles Systems
-            serializationObject.particleSystems = [];
-            for (index = 0; index < scene.particleSystems.length; index++) {
-                serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
-            }
-
-            // Lens flares
-            serializationObject.lensFlareSystems = [];
-            for (index = 0; index < scene.lensFlareSystems.length; index++) {
-                serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
-            }
-
-            // Shadows
-            serializationObject.shadowGenerators = [];
-            for (index = 0; index < scene.lights.length; index++) {
-                light = scene.lights[index];
-
-                if (light.getShadowGenerator()) {
-                    serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
-                }
-            }
-
-            return serializationObject;
-        }
-
-        public static SerializeMesh(toSerialize: any /* Mesh || Mesh[] */, withParents: boolean = false, withChildren: boolean = false): any {
-            var serializationObject: any = {};
-
-            toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
-
-            if (withParents || withChildren) {
-                //deliberate for loop! not for each, appended should be processed as well.
-                for (var i = 0; i < toSerialize.length; ++i) {
-                    if (withChildren) {
-                        toSerialize[i].getDescendants().forEach((node) => {
-                            if (node instanceof Mesh && (toSerialize.indexOf(node) < 0)) {
-                                toSerialize.push(node);
-                            }
-                        });
-                    }
-                    //make sure the array doesn't contain the object already
-                    if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
-                        toSerialize.push(toSerialize[i].parent);
-                    }
-                }
-            }
-
-            toSerialize.forEach((mesh: Mesh) => {
-                finalizeSingleMesh(mesh, serializationObject);
-            });
-
-            return serializationObject;
-        }
-    }
+module BABYLON {  
+    var serializedGeometries: Geometry[] = [];
+    var serializeGeometry = (geometry: Geometry, serializationGeometries: any): any => {
+        if (serializedGeometries[geometry.id]) {
+            return;
+        }
+        if (geometry instanceof Geometry.Primitives.Box) {
+            serializationGeometries.boxes.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.Sphere) {
+            serializationGeometries.spheres.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.Cylinder) {
+            serializationGeometries.cylinders.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.Torus) {
+            serializationGeometries.toruses.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.Ground) {
+            serializationGeometries.grounds.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.Plane) {
+            serializationGeometries.planes.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives.TorusKnot) {
+            serializationGeometries.torusKnots.push(geometry.serialize());
+        }
+        else if (geometry instanceof Geometry.Primitives._Primitive) {
+            throw new Error("Unknown primitive type");
+        }
+        else {
+            serializationGeometries.vertexData.push(geometry.serializeVerticeData());
+        }
+
+        serializedGeometries[geometry.id] = true;
+    };
+
+    var serializeMesh = (mesh: Mesh, serializationScene: any): any => {
+        var serializationObject: any = {};
+
+        serializationObject.name = mesh.name;
+        serializationObject.id = mesh.id;
+
+        if (Tags.HasTags(mesh)) {
+            serializationObject.tags = Tags.GetTags(mesh);
+        }
+
+        serializationObject.position = mesh.position.asArray();
+
+        if (mesh.rotationQuaternion) {
+            serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
+        } else if (mesh.rotation) {
+            serializationObject.rotation = mesh.rotation.asArray();
+        }
+
+        serializationObject.scaling = mesh.scaling.asArray();
+        serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
+
+        serializationObject.isEnabled = mesh.isEnabled();
+        serializationObject.isVisible = mesh.isVisible;
+        serializationObject.infiniteDistance = mesh.infiniteDistance;
+        serializationObject.pickable = mesh.isPickable;
+
+        serializationObject.receiveShadows = mesh.receiveShadows;
+
+        serializationObject.billboardMode = mesh.billboardMode;
+        serializationObject.visibility = mesh.visibility;
+
+        serializationObject.checkCollisions = mesh.checkCollisions;
+
+        // Parent
+        if (mesh.parent) {
+            serializationObject.parentId = mesh.parent.id;
+        }
+
+        // Geometry
+        var geometry = mesh._geometry;
+        if (geometry) {
+            var geometryId = geometry.id;
+            serializationObject.geometryId = geometryId;
+
+            if (!mesh.getScene().getGeometryByID(geometryId)) {
+                // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
+                serializeGeometry(geometry, serializationScene.geometries);
+            }
+
+            // SubMeshes
+            serializationObject.subMeshes = [];
+            for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                var subMesh = mesh.subMeshes[subIndex];
+
+                serializationObject.subMeshes.push({
+                    materialIndex: subMesh.materialIndex,
+                    verticesStart: subMesh.verticesStart,
+                    verticesCount: subMesh.verticesCount,
+                    indexStart: subMesh.indexStart,
+                    indexCount: subMesh.indexCount
+                });
+            }
+        }
+
+        // Material
+        if (mesh.material) {
+            serializationObject.materialId = mesh.material.id;
+        } else {
+            mesh.material = null;
+        }
+
+        // Skeleton
+        if (mesh.skeleton) {
+            serializationObject.skeletonId = mesh.skeleton.id;
+        }
+
+        // Physics
+        if (mesh.getPhysicsImpostor() !== PhysicsEngine.NoImpostor) {
+            serializationObject.physicsMass = mesh.getPhysicsMass();
+            serializationObject.physicsFriction = mesh.getPhysicsFriction();
+            serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
+
+            switch (mesh.getPhysicsImpostor()) {
+                case PhysicsEngine.BoxImpostor:
+                    serializationObject.physicsImpostor = 1;
+                    break;
+                case PhysicsEngine.SphereImpostor:
+                    serializationObject.physicsImpostor = 2;
+                    break;
+            }
+        }
+
+        // Instances
+        serializationObject.instances = [];
+        for (var index = 0; index < mesh.instances.length; index++) {
+            var instance = mesh.instances[index];
+            var serializationInstance = {
+                name: instance.name,
+                position: instance.position.asArray(),
+                rotation: instance.rotation.asArray(),
+                rotationQuaternion: instance.rotationQuaternion.asArray(),
+                scaling: instance.scaling.asArray()
+            };
+            serializationObject.instances.push(serializationInstance);
+
+            // Animations
+            Animation.AppendSerializedAnimations(instance, serializationInstance);
+        }
+
+        // Animations
+        Animation.AppendSerializedAnimations(mesh, serializationObject);
+
+        // Layer mask
+        serializationObject.layerMask = mesh.layerMask;
+
+        return serializationObject;
+    };
+
+    var finalizeSingleMesh = (mesh: Mesh, serializationObject: any) => {
+        //only works if the mesh is already loaded
+        if (mesh.delayLoadState === Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === Engine.DELAYLOADSTATE_NONE) {
+            //serialize material
+            if (mesh.material) {
+                if (mesh.material instanceof StandardMaterial) {
+                    serializationObject.materials = serializationObject.materials || [];
+                    if (!serializationObject.materials.some(mat => (mat.id === mesh.material.id))) {
+                        serializationObject.materials.push(mesh.material.serialize());
+                    }
+                } else if (mesh.material instanceof MultiMaterial) {
+                    serializationObject.multiMaterials = serializationObject.multiMaterials || [];
+                    if (!serializationObject.multiMaterials.some(mat => (mat.id === mesh.material.id))) {
+                        serializationObject.multiMaterials.push(mesh.material.serialize());
+                    }
+
+                }
+            }
+            //serialize geometry
+            var geometry = mesh._geometry;
+            if (geometry) {
+                if (!serializationObject.geometries) {
+                    serializationObject.geometries = {};
+
+                    serializationObject.geometries.boxes = [];
+                    serializationObject.geometries.spheres = [];
+                    serializationObject.geometries.cylinders = [];
+                    serializationObject.geometries.toruses = [];
+                    serializationObject.geometries.grounds = [];
+                    serializationObject.geometries.planes = [];
+                    serializationObject.geometries.torusKnots = [];
+                    serializationObject.geometries.vertexData = [];
+                }
+
+                serializeGeometry(geometry, serializationObject.geometries);
+            }
+            // Skeletons
+            if (mesh.skeleton) {
+                serializationObject.skeletons = serializationObject.skeletons || [];
+                serializationObject.skeletons.push(mesh.skeleton.serialize());
+            }
+
+            //serialize the actual mesh
+            serializationObject.meshes = serializationObject.meshes || [];
+            serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
+        }
+    }
+
+    export class SceneSerializer {
+        public static Serialize(scene: Scene): any {
+            var serializationObject: any = {};
+
+            // Scene
+            serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
+            serializationObject.autoClear = scene.autoClear;
+            serializationObject.clearColor = scene.clearColor.asArray();
+            serializationObject.ambientColor = scene.ambientColor.asArray();
+            serializationObject.gravity = scene.gravity.asArray();
+            serializationObject.collisionsEnabled = scene.collisionsEnabled;
+            serializationObject.workerCollisions = scene.workerCollisions;
+            
+            // Fog
+            if (scene.fogMode && scene.fogMode !== 0) {
+                serializationObject.fogMode = scene.fogMode;
+                serializationObject.fogColor = scene.fogColor.asArray();
+                serializationObject.fogStart = scene.fogStart;
+                serializationObject.fogEnd = scene.fogEnd;
+                serializationObject.fogDensity = scene.fogDensity;
+            }
+            
+            //Physics
+            if (scene.isPhysicsEnabled()) {
+                serializationObject.physicsEnabled = true;
+                serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
+                serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
+            }
+
+            // Lights
+            serializationObject.lights = [];
+            var index: number;
+            var light: Light;
+            for (index = 0; index < scene.lights.length; index++) {
+                light = scene.lights[index];
+                serializationObject.lights.push(light.serialize());
+            }
+
+            // Cameras
+            serializationObject.cameras = [];
+            for (index = 0; index < scene.cameras.length; index++) {
+                var camera = scene.cameras[index];
+                serializationObject.cameras.push(camera.serialize());
+            }
+
+            if (scene.activeCamera) {
+                serializationObject.activeCameraID = scene.activeCamera.id;
+            }
+
+            // Materials
+            serializationObject.materials = [];
+            serializationObject.multiMaterials = [];
+            var material: Material;
+            for (index = 0; index < scene.materials.length; index++) {
+                material = scene.materials[index];
+                serializationObject.materials.push(material.serialize());
+            }
+
+            // MultiMaterials
+            serializationObject.multiMaterials = [];
+            for (index = 0; index < scene.multiMaterials.length; index++) {
+                var multiMaterial = scene.multiMaterials[index];
+                serializationObject.multiMaterials.push(multiMaterial.serialize());
+            }
+
+            for (index = 0; index < scene.materials.length; index++) {
+                material = scene.materials[index];
+                serializationObject.materials.push(material.serialize());
+            }
+
+            // Skeletons
+            serializationObject.skeletons = [];
+            for (index = 0; index < scene.skeletons.length; index++) {
+                serializationObject.skeletons.push(scene.skeletons[index].serialize());
+            }
+
+            // Geometries
+            serializationObject.geometries = {};
+
+            serializationObject.geometries.boxes = [];
+            serializationObject.geometries.spheres = [];
+            serializationObject.geometries.cylinders = [];
+            serializationObject.geometries.toruses = [];
+            serializationObject.geometries.grounds = [];
+            serializationObject.geometries.planes = [];
+            serializationObject.geometries.torusKnots = [];
+            serializationObject.geometries.vertexData = [];
+
+            serializedGeometries = [];
+            var geometries = scene.getGeometries();
+            for (index = 0; index < geometries.length; index++) {
+                var geometry = geometries[index];
+
+                if (geometry.isReady()) {
+                    serializeGeometry(geometry, serializationObject.geometries);
+                }
+            }
+
+            // Meshes
+            serializationObject.meshes = [];
+            for (index = 0; index < scene.meshes.length; index++) {
+                var abstractMesh = scene.meshes[index];
+
+                if (abstractMesh instanceof Mesh) {
+                    var mesh = abstractMesh;
+                    if (mesh.delayLoadState === Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === Engine.DELAYLOADSTATE_NONE) {
+                        serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
+                    }
+                }
+            }
+
+            // Particles Systems
+            serializationObject.particleSystems = [];
+            for (index = 0; index < scene.particleSystems.length; index++) {
+                serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
+            }
+
+            // Lens flares
+            serializationObject.lensFlareSystems = [];
+            for (index = 0; index < scene.lensFlareSystems.length; index++) {
+                serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
+            }
+
+            // Shadows
+            serializationObject.shadowGenerators = [];
+            for (index = 0; index < scene.lights.length; index++) {
+                light = scene.lights[index];
+
+                if (light.getShadowGenerator()) {
+                    serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
+                }
+            }
+
+            return serializationObject;
+        }
+
+        public static SerializeMesh(toSerialize: any /* Mesh || Mesh[] */, withParents: boolean = false, withChildren: boolean = false): any {
+            var serializationObject: any = {};
+
+            toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
+
+            if (withParents || withChildren) {
+                //deliberate for loop! not for each, appended should be processed as well.
+                for (var i = 0; i < toSerialize.length; ++i) {
+                    if (withChildren) {
+                        toSerialize[i].getDescendants().forEach((node) => {
+                            if (node instanceof Mesh && (toSerialize.indexOf(node) < 0)) {
+                                toSerialize.push(node);
+                            }
+                        });
+                    }
+                    //make sure the array doesn't contain the object already
+                    if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
+                        toSerialize.push(toSerialize[i].parent);
+                    }
+                }
+            }
+
+            toSerialize.forEach((mesh: Mesh) => {
+                finalizeSingleMesh(mesh, serializationObject);
+            });
+
+            return serializationObject;
+        }
+    }
 }